import logging
import json
from datetime import timedelta
from homeassistant.helpers.entity import Entity
from homeassistant.util import dt
from homeassistant.core import callback
from homeassistant.const import STATE_OK, STATE_UNKNOWN
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.components.cast.const import (
    SIGNAL_CAST_DISCOVERED,
    SIGNAL_CAST_REMOVED,
)

_LOGGER = logging.getLogger(__name__)

SENSOR_SCAN_INTERVAL_SECS = 10
SCAN_INTERVAL = timedelta(seconds=SENSOR_SCAN_INTERVAL_SECS)


def setup_platform(hass, config, add_devices, discovery_info=None):
    add_devices([ChromecastDevicesSensor(hass)])

class ChromecastDevicesSensor(Entity):

    def __init__(self, hass):
        self.hass = hass
        self._state = STATE_UNKNOWN
        self._discovered_casts = {}
        self._attributes = {
            'devices_json': [],
            'devices': [],
            'last_update': None
        }

        self.async_on_remove(
            async_dispatcher_connect(hass, SIGNAL_CAST_DISCOVERED, self.async_cast_discovered))
        self.async_on_remove(
            async_dispatcher_connect(hass, SIGNAL_CAST_REMOVED, self.async_cast_removed))

        _LOGGER.debug('initiating sensor')

    @callback
    def async_cast_discovered(self, cast_info):
        self._discovered_casts[cast_info.uuid] = cast_info

    @callback
    def async_cast_removed(self, cast_info):
        self._discovered_casts.pop(cast_info.uuid, None)

    @property
    def name(self):
        return 'Chromecast Devices'

    @property
    def state(self):
        return self._state

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return self._attributes

    def update(self):
        _LOGGER.debug('Getting chromecast devices')

        known_devices = list(self._discovered_casts.values())

        _LOGGER.debug('devices %s', known_devices)

        chromecasts = [
            {
                "uuid": cast.uuid,
                "model_name": cast.model_name,
                "name": cast.friendly_name,
                'manufacturer': cast.manufacturer
            }
            for cast in known_devices
        ]

        self._attributes['devices_json'] = json.dumps(chromecasts, ensure_ascii=False)
        self._attributes['devices'] = chromecasts
        self._attributes['last_update'] = dt.now().isoformat('T')
        self._state = STATE_OK



