"""Details about printers which are connected to CUPS."""
from datetime import timedelta
import importlib
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

_LOGGER = logging.getLogger(__name__)

ATTR_MARKER_TYPE = "marker_type"
ATTR_MARKER_LOW_LEVEL = "marker_low_level"
ATTR_MARKER_HIGH_LEVEL = "marker_high_level"
ATTR_PRINTER_NAME = "printer_name"
ATTR_DEVICE_URI = "device_uri"
ATTR_PRINTER_INFO = "printer_info"
ATTR_PRINTER_IS_SHARED = "printer_is_shared"
ATTR_PRINTER_LOCATION = "printer_location"
ATTR_PRINTER_MODEL = "printer_model"
ATTR_PRINTER_STATE_MESSAGE = "printer_state_message"
ATTR_PRINTER_STATE_REASON = "printer_state_reason"
ATTR_PRINTER_TYPE = "printer_type"
ATTR_PRINTER_URI_SUPPORTED = "printer_uri_supported"

CONF_PRINTERS = "printers"
CONF_IS_CUPS_SERVER = "is_cups_server"

DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 631
DEFAULT_IS_CUPS_SERVER = True

ICON_PRINTER = "mdi:printer"
ICON_MARKER = "mdi:water"

SCAN_INTERVAL = timedelta(minutes=1)

PRINTER_STATES = {3: "idle", 4: "printing", 5: "stopped"}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_PRINTERS): vol.All(cv.ensure_list, [cv.string]),
        vol.Optional(CONF_IS_CUPS_SERVER, default=DEFAULT_IS_CUPS_SERVER): cv.boolean,
        vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
        vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
    }
)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the CUPS sensor."""
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    printers = config.get(CONF_PRINTERS)
    is_cups = config.get(CONF_IS_CUPS_SERVER)

    if is_cups:
        data = CupsData(host, port, None)
        data.update()
        if data.available is False:
            _LOGGER.error("Unable to connect to CUPS server: %s:%s", host, port)
            raise PlatformNotReady()

        dev = []
        for printer in printers:
            if printer not in data.printers:
                _LOGGER.error("Printer is not present: %s", printer)
                continue
            dev.append(CupsSensor(data, printer))

            if "marker-names" in data.attributes[printer]:
                for marker in data.attributes[printer]["marker-names"]:
                    dev.append(MarkerSensor(data, printer, marker, True))

        add_entities(dev, True)
        return

    data = CupsData(host, port, printers)
    data.update()
    if data.available is False:
        _LOGGER.error("Unable to connect to IPP printer: %s:%s", host, port)
        raise PlatformNotReady()

    dev = []
    for printer in printers:
        dev.append(IPPSensor(data, printer))

        if "marker-names" in data.attributes[printer]:
            for marker in data.attributes[printer]["marker-names"]:
                dev.append(MarkerSensor(data, printer, marker, False))

    add_entities(dev, True)


class CupsSensor(Entity):
    """Representation of a CUPS sensor."""

    def __init__(self, data, printer):
        """Initialize the CUPS sensor."""
        self.data = data
        self._name = printer
        self._printer = None
        self._available = False

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def state(self):
        """Return the state of the sensor."""
        if self._printer is None:
            return None

        key = self._printer["printer-state"]
        return PRINTER_STATES.get(key, key)

    @property
    def available(self):
        """Return True if entity is available."""
        return self._available

    @property
    def icon(self):
        """Return the icon to use in the frontend, if any."""
        return ICON_PRINTER

    @property
    def device_state_attributes(self):
        """Return the state attributes of the sensor."""
        if self._printer is None:
            return None

        return {
            ATTR_DEVICE_URI: self._printer["device-uri"],
            ATTR_PRINTER_INFO: self._printer["printer-info"],