# -*- coding: utf-8 -*-
# Moovida - Home multimedia server
# Copyright (C) 2006-2009 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Moovida with Fluendo's plugins.
#
# The GPL part of Moovida is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Moovida" in the root directory of this distribution package
# for details on that license.

from elisa.core.common import application
from elisa.core.media_uri import MediaUri
from elisa.core.utils import defer
from elisa.core.utils.i18n import install_translation

from elisa.plugins.poblesec.base.list import BaseListController, GenericListViewMode
from elisa.plugins.poblesec.base.preview_list import MenuItemPreviewListController
from elisa.plugins.poblesec.base.coverflow import ImageWithReflectionCoverflowController
from elisa.plugins.poblesec.base.grid import GridItemGridController
from elisa.plugins.poblesec.base.list_switcher import ListSwitcherController

from elisa.plugins.shoutcast.models import ShoutcastGenreModel, \
                                           ShoutcastRadioStationModel


_ = install_translation('shoutcast')
_p = install_translation('poblesec')


def shoutcast_decorator(controller):
    controller.append_plugin('shoutcast', _('Shoutcast'), '/poblesec/shoutcast')
    return defer.succeed(None)


class GenericShoutcastController(BaseListController):
    def initialize(self, uri=None, station=None):
        self.uri = uri
        self.station = station
        dfr = super(GenericShoutcastController, self).initialize()
        return dfr

    def is_empty(self):
        return super(GenericShoutcastController, self).is_empty() and self.station is None

    def node_clicked(self, widget, item):
        if isinstance(item, ShoutcastGenreModel):
            browser = self.frontend.retrieve_controllers('/poblesec/browser')[0]
            browser.history.append_controller(self.path, item.name, uri=item.uri)
        elif isinstance(item, ShoutcastRadioStationModel):
            return self.play_station(item)

    def play_station(self, station):
        resource, dfr = application.resource_manager.get(station.get_playable, station)

        def play(station):
            player = self.frontend.retrieve_controllers('/poblesec/music_player')[0]
            player.player.play_model(station)

            main = self.frontend.retrieve_controllers('/poblesec')[0]
            main.show_music_player()

        dfr.addCallback(play)


class ShoutcastController(GenericShoutcastController):

    default_uri = MediaUri("shoutcast://genres")

    def initialize(self, uri=default_uri, station=None):
        dfr = super(ShoutcastController, self).initialize(uri=uri, station=station)

        if uri and not station:
            def resource_loaded(resource):
                if isinstance(resource, ShoutcastGenreModel):
                    self.model.extend(resource.stations)
                else:
                    # FIXME: fallbacks on a list of genres
                    self.model.extend(resource.genres)
                return self

            def load_resource(controller):
                resource, get_dfr = application.resource_manager.get(self.uri)
                return get_dfr

            dfr.addCallback(load_resource)
            dfr.addCallback(resource_loaded)

        return dfr


class ShoutcastViewMode(GenericListViewMode):

    """
    Implementation of the common view modes API.
    """

    def get_label(self, item):
        return defer.succeed(item.name)

    def get_default_image(self, item):
        resource = None
        if isinstance(item, ShoutcastGenreModel):
            resource = 'elisa.plugins.poblesec.glyphs.small.devices_shares'
        elif isinstance(item, ShoutcastRadioStationModel):
            resource = 'elisa.plugins.poblesec.glyphs.small.music'
        return resource

    def get_image(self, item, theme):
        return None

    def get_preview_image(self, item, theme):
        return None


class ShoutcastPreviewListController(ShoutcastController, MenuItemPreviewListController):
    view_mode = ShoutcastViewMode
    item_widget_kwargs = {'with_artwork_box': False}

class ShoutcastCoverflowController(ShoutcastController, ImageWithReflectionCoverflowController):
    view_mode = ShoutcastViewMode

class ShoutcastGridController(ShoutcastController, GridItemGridController):
    view_mode = ShoutcastViewMode

class ShoutcastListSwitcherController(ListSwitcherController):
    modes = [ShoutcastPreviewListController,
             ShoutcastCoverflowController,
             ShoutcastGridController]
    default_mode = ShoutcastPreviewListController
    crumbs_logo = "elisa.plugins.shoutcast.logo"


def use_me_hook(frontend):
    """
    'Use me' hook that takes the user to the Music/Internet/Shoutcast section.

    @param frontend: the current frontend (poblesec)
    @type frontend:  L{elisa.plugins.pigment.pigment_frontend.PigmentFrontend}

    @return:         a deferred fired when the action is complete
    @rtype:          L{twisted.internet.defer.Deferred}
    """
    browser = frontend.retrieve_controllers('/poblesec/browser')[0]
    paths = [('/poblesec/internet_menu', _p('INTERNET MEDIA'), {}),
             ('/poblesec/radio/internet', _p('Radio'), {}),
             ('/poblesec/shoutcast', _('Shoutcast'), {})]
    return browser.navigate(paths)
