"""
Support for testing internet speed via Fast.com.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/fastdotcom/
"""

import logging
from datetime import timedelta

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_UPDATE_INTERVAL
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import async_track_time_interval

REQUIREMENTS = ['fastdotcom==0.0.3']

DOMAIN = 'fastdotcom'
DATA_UPDATED = '{}_data_updated'.format(DOMAIN)

_LOGGER = logging.getLogger(__name__)

CONF_MANUAL = 'manual'

DEFAULT_INTERVAL = timedelta(hours=1)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Optional(CONF_UPDATE_INTERVAL, default=DEFAULT_INTERVAL):
            vol.All(
                cv.time_period, cv.positive_timedelta
            ),
        vol.Optional(CONF_MANUAL, default=False): cv.boolean,
    })
}, extra=vol.ALLOW_EXTRA)


async def async_setup(hass, config):
    """Set up the Fast.com component."""
    conf = config[DOMAIN]
    data = hass.data[DOMAIN] = SpeedtestData(
        hass, conf[CONF_UPDATE_INTERVAL], conf[CONF_MANUAL]
    )

    def update(call=None):
        """Service call to manually update the data."""
        data.update()

    hass.services.async_register(DOMAIN, 'speedtest', update)

    hass.async_create_task(
        async_load_platform(hass, 'sensor', DOMAIN, {}, config)
    )

    return True


class SpeedtestData:
    """Get the latest data from fast.com."""

    def __init__(self, hass, interval, manual):
        """Initialize the data object."""
        self.data = None
        self._hass = hass
        if not manual:
            async_track_time_interval(self._hass, self.update, interval)

    def update(self):
        """Get the latest data from fast.com."""
        from fastdotcom import fast_com
        _LOGGER.debug("Executing fast.com speedtest")
        self.data = {'download': fast_com()}
        dispatcher_send(self._hass, DATA_UPDATED)

"""
Support for testing internet speed via Fast.com.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/fastdotcom/
"""

import logging
from datetime import timedelta

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_UPDATE_INTERVAL
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import async_track_time_interval

REQUIREMENTS = ['fastdotcom==0.0.3']

DOMAIN = 'fastdotcom'
DATA_UPDATED = '{}_data_updated'.format(DOMAIN)

_LOGGER = logging.getLogger(__name__)

CONF_MANUAL = 'manual'

DEFAULT_INTERVAL = timedelta(hours=1)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Optional(CONF_UPDATE_INTERVAL, default=DEFAULT_INTERVAL):
            vol.All(
                cv.time_period, cv.positive_timedelta
            ),
        vol.Optional(CONF_MANUAL, default=False): cv.boolean,
    })
}, extra=vol.ALLOW_EXTRA)


async def async_setup(hass, config):
    """Set up the Fast.com component."""
    conf = config[DOMAIN]
    data = hass.data[DOMAIN] = SpeedtestData(hass)

    if not conf[CONF_MANUAL]:
        async_track_time_interval(
            hass, data.update, conf[CONF_UPDATE_INTERVAL]
        )

    def update(call=None):
        """Service call to manually update the data."""
        data.update()

    hass.services.async_register(DOMAIN, 'speedtest', update)

    hass.async_create_task(
        async_load_platform(hass, 'sensor', DOMAIN, {}, config)
    )

    return True


class SpeedtestData:
    """Get the latest data from fast.com."""

    def __init__(self, hass):
        """Initialize the data object."""
        self.data = None
        self._hass = hass

    def update(self, now=None):
        """Get the latest data from fast.com."""
        from fastdotcom import fast_com
        _LOGGER.debug("Executing fast.com speedtest")
        self.data = {'download': fast_com()}
        dispatcher_send(self._hass, DATA_UPDATED)

Clean up fastdotcom by doing time tracking outside of the data object (#20725)