from pylaunchr.builder.factory import ScreenFromFileFactory
from pylaunchr.builder.path import module_relative_path
from pylaunchr.fragments.menu import FragmentMenuHandler

from ..utils import get_data


class NetflixFragmentMenuHandler(FragmentMenuHandler):

    def __init__(self, menu, fragment_holder, context):
        super().__init__(menu, fragment_holder)
        self.genres = get_data(context).genres
        self.genres.add_listener(self)
        self.fragment_holder = fragment_holder
        self.context = context

    def init(self):
        self._update()

    def _update(self):
        fragments = []

        def make_fragment(widget, title, icon):
            return {"widget": widget, "title": title, "icon": icon}

        fragments.append(make_fragment("netflix-browse", "Browse", "browser"))

        for genre in self.genres:
            fragments.append({
                "widget": "netflix-genre",
                "title": genre.title,
                "icon": "tv",
                "genre": genre})

        self.menu.store.set_items(fragments)

    def activated(self, item):
        self._select_fragment(True)

    def selected_changed(self, index):
        self._select_fragment(False)

    def _load_genre(self, item, focus):
        view = self.context.get_widget("netflix-genre-view")
        view.store.set_store(self.genres.get_genre_title_store(item["genre"]))

        title = self.context.get_widget("netflix-genre-title")
        title.set_text(item["title"])

        self.fragment_holder.activated["title"] = item["title"]
        self.fragment_holder.select_by_name(item["widget"], focus=focus)

    def _select_fragment(self, focus):
        item = self.menu.get_selected_item()
        if item:
            self.fragment_holder.select_by_name(item["widget"], focus=focus)

            if item["widget"] == "netflix-genre":
                self._load_genre(item, focus)

    def store_changed(self, store):
        assert store is self.genres
        self._update()

    def start(self):
        self.menu.focus()
        self.menu.select(0)


class NetflixScreenFactory(ScreenFromFileFactory):

    def __init__(self, context):
        super().__init__(context, module_relative_path("screen.xml"))
