"""
homeassistant.components.media_player.squeezebox
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides an interface to the Logitech SqueezeBox API

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.squeezebox/
"""
import logging
import telnetlib
import urllib.parse

from homeassistant.components.media_player import (
    MediaPlayerDevice, SUPPORT_PAUSE, SUPPORT_SEEK, SUPPORT_VOLUME_SET,
    SUPPORT_VOLUME_MUTE, SUPPORT_PREVIOUS_TRACK, SUPPORT_NEXT_TRACK,
    SUPPORT_TURN_ON, SUPPORT_TURN_OFF,
    MEDIA_TYPE_MUSIC, DOMAIN)

from homeassistant.const import (
    CONF_HOST, CONF_USERNAME, CONF_PASSWORD,
    STATE_IDLE, STATE_PLAYING, STATE_PAUSED, STATE_OFF, STATE_UNKNOWN)

_LOGGER = logging.getLogger(__name__)

SUPPORT_SQUEEZEBOX = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | \
    SUPPORT_VOLUME_MUTE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \
    SUPPORT_SEEK | SUPPORT_TURN_ON | SUPPORT_TURN_OFF


def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the squeezebox platform. """
    if not config.get(CONF_HOST):
        _LOGGER.error(
            "Missing required configuration items in %s: %s",
            DOMAIN,
            CONF_HOST)
        return False

    lms = LogitechMediaServer(
        config.get(CONF_HOST),
        config.get('port', '9090'),
        config.get(CONF_USERNAME),
        config.get(CONF_PASSWORD))

    if not lms.init_success:
        return False

    add_devices(lms.create_players())

    return True


class LogitechMediaServer(object):
    """ Represents a Logitech media server. """

    def __init__(self, host, port, username, password):
        self.host = host
        self.port = port
        self._username = username
        self._password = password
        self.http_port = self._get_http_port()
        self.init_success = True if self.http_port else False

    def _get_http_port(self):
        """ Get http port from media server, it is used to get cover art. """
        http_port = None
        try:
            http_port = self.query('pref', 'httpport', '?')
            if not http_port:
                _LOGGER.error(
                    "Unable to read data from server %s:%s",
                    self.host,
                    self.port)
                return
            return http_port
        except ConnectionError as ex:
            _LOGGER.error(
                "Failed to connect to server %s:%s - %s",
                self.host,
                self.port,
                ex)
            return

    def create_players(self):
        """ Create a list of SqueezeBoxDevices connected to the LMS. """
        players = []
        count = self.query('player', 'count', '?')
        for index in range(0, int(count)):
            player_id = self.query('player', 'id', str(index), '?')