# -*- coding: utf-8 -*-
"""Pages over the Home sections (the media detail, the genre page) belong to the section they were opened in:
Window(Home).Property(milionar.<page>.owner) = its menu item, and the skin shows the page only while the menu shows that
section (gen_cinema.OVERLAYS). A trip to the menu or another section keeps the page where it was.

A page opens at once and fills while the user watches (Loading): never a click without an answer, never the content of
the previous page."""
import threading
import uuid

import xbmc
import xbmcgui

from wcs.genres.progress import Progress


def menu_item():
    """The section the Home menu shows (its menu item id); '' while another window is active."""
    return xbmc.getInfoLabel('Container(9000).ListItem.Property(id)')


def here(prefix):
    """The page with the Window(Home) property prefix `prefix` (milionar.genre.) is open in the section on screen."""
    home = xbmcgui.Window(10000)
    return home.getProperty(prefix + 'active') == 'true' and home.getProperty(prefix + 'owner') == menu_item()


class Stale(Exception):
    """A newer load of the same page (another title, another filter, Zpět) took over: this one stops quietly."""


class Loading(object):
    """A load of a page that is already on screen. <prefix>loading holds the id of the newest load: while it is set
    and the page has no row yet the skin draws Kodi's spinner where the rows will be (gen_cinema.LOADING_SPINNER), and
    Kodi's background progress names the step from the first moment. A newer load (or cancel) replaces the id, so
    every later step of this one raises Stale and it never writes over the page (a step reported from a worker thread
    only stops showing)."""

    def __init__(self, prefix, heading, message):
        self.prefix, self.message = prefix, message
        self.id = uuid.uuid4().hex[:12]
        self.progress = Progress(heading)
        self.home = xbmcgui.Window(10000)
        self.thread = threading.get_ident()

    def current(self):
        return self.home.getProperty(self.prefix + 'loading') == self.id

    def check(self):
        if not self.current():
            raise Stale()

    def update(self, percent, message):
        if threading.get_ident() == self.thread:
            self.check()
        elif not self.current():
            return
        self.progress.update(percent, message)

    def __enter__(self):
        self.home.setProperty(self.prefix + 'loading', self.id)
        self.progress.update(0, self.message)
        return self

    def __exit__(self, exc_type, _exc, _tb):
        self.progress.close()
        if self.current():
            self.home.clearProperty(self.prefix + 'loading')
        return exc_type is Stale


def cancel(prefix):
    """Leaving the page: a load still running for it stops at its next step."""
    xbmcgui.Window(10000).clearProperty(prefix + 'loading')
