"""Support for IGN Sismologia (Earthquakes) Feeds."""
from datetime import timedelta
import logging
from typing import Optional

from georss_ign_sismologia_client import IgnSismologiaFeedManager
import voluptuous as vol

from homeassistant.components.geo_location import PLATFORM_SCHEMA, GeolocationEvent
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    CONF_LATITUDE,
    CONF_LONGITUDE,
    CONF_RADIUS,
    CONF_SCAN_INTERVAL,
    EVENT_HOMEASSISTANT_START,
    LENGTH_KILOMETERS,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.event import track_time_interval

_LOGGER = logging.getLogger(__name__)

ATTR_EXTERNAL_ID = "external_id"
ATTR_IMAGE_URL = "image_url"
ATTR_MAGNITUDE = "magnitude"
ATTR_PUBLICATION_DATE = "publication_date"
ATTR_REGION = "region"
ATTR_TITLE = "title"

CONF_MINIMUM_MAGNITUDE = "minimum_magnitude"

DEFAULT_MINIMUM_MAGNITUDE = 0.0
DEFAULT_RADIUS_IN_KM = 50.0

SCAN_INTERVAL = timedelta(minutes=5)

SOURCE = "ign_sismologia"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_LATITUDE): cv.latitude,
        vol.Optional(CONF_LONGITUDE): cv.longitude,
        vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS_IN_KM): vol.Coerce(float),
        vol.Optional(
            CONF_MINIMUM_MAGNITUDE, default=DEFAULT_MINIMUM_MAGNITUDE
        ): cv.positive_float,
    }
)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the IGN Sismologia Feed platform."""
    scan_interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
    coordinates = (
        config.get(CONF_LATITUDE, hass.config.latitude),
        config.get(CONF_LONGITUDE, hass.config.longitude),
    )
    radius_in_km = config[CONF_RADIUS]
    minimum_magnitude = config[CONF_MINIMUM_MAGNITUDE]
    # Initialize the entity manager.
    feed = IgnSismologiaFeedEntityManager(
        hass, add_entities, scan_interval, coordinates, radius_in_km, minimum_magnitude
    )

    def start_feed_manager(event):
        """Start feed manager."""
        feed.startup()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_feed_manager)


class IgnSismologiaFeedEntityManager:
    """Feed Entity Manager for IGN Sismologia GeoRSS feed."""

    def __init__(
        self,
        hass,
        add_entities,
        scan_interval,
        coordinates,
        radius_in_km,