# -*- coding: utf-8 -*-
"""Quick TMDb search pick for "Add movie / series" (UI.add_movie / UI.add_series).

The dialog opens at once and searches in the background: page 1 fills the list, later pages append, and every
title's details (tagline, runtime, genres) arrive in the background, the focused one first. On another skin the
plain Kodi select stays.
"""
import queue
import threading

import xbmc
import xbmcgui

from wcs.skin import family

XML = 'skin/DialogMilionarTitlePicker.xml'
S_SEARCHING = 35610
POSTER = 'https://image.tmdb.org/t/p/w342'
PAGES = 3                     # 60 titles at most; page 1 is on screen before the others are asked for
WORKERS = 3
BACK = (xbmcgui.ACTION_NAV_BACK, xbmcgui.ACTION_PREVIOUS_MENU)
CANCEL = 7
LIST = 6                      # never 2/3/4: Kodi's WindowXML swallows clicks of those ids (its view/sort buttons)


def _title(media, result):
    return result.get('title' if media == 'movie' else 'name') or ''


def _year(media, result):
    return (result.get('release_date' if media == 'movie' else 'first_air_date') or '')[:4]


def _label(media, result):
    year = _year(media, result)
    return '{} ({})'.format(_title(media, result), year) if year else _title(media, result)


def _rating(result):
    if not result.get('vote_count') or not result.get('vote_average'):
        return ''
    text = '{:.1f}'.format(float(result['vote_average']))
    return text.replace('.', ',') if xbmc.getLanguage(xbmc.ISO_639_1) in ('cs', 'sk') else text


def _runtime(minutes):
    if not minutes:
        return ''
    return '{} h {} min'.format(minutes // 60, minutes % 60) if minutes >= 60 else '{} min'.format(minutes)


def _meta(media, result, data):
    """'1984 · 1 h 47 min' for a movie, '2008–2013 · 47 min' for a series."""
    year = _year(media, result)
    if media == 'movie':
        parts = [year, _runtime(data.get('runtime'))]
    else:
        last = (data.get('last_air_date') or '')[:4]
        span = year + ('–' if data.get('in_production') else '–' + last if last and last != year else '')
        parts = [span if year else '', _runtime((data.get('episode_run_time') or [0])[0])]
    return ' · '.join(p for p in parts if p)


def search(media, query, page, addon):
    from urllib.parse import quote_plus
    import requests
    from wcs.metadata.TMDbClient import get_tmdb_api_key
    url = 'https://api.themoviedb.org/3/search/{}?api_key={}&language=cs-CZ&query={}&page={}'.format(
        media, get_tmdb_api_key(addon), quote_plus(query), page)
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    return response.json()


def details(media, tmdb_id, addon):
    """Cached library metadata when present, else one plain request (not cached: a search result is no library title).
    Czech first; a missing plot or tagline falls back to English."""
    from wcs.library2 import meta
    from wcs.metadata.TMDbClient import fetch_tmdb_item_detail
    key = meta.key_movie(tmdb_id) if media == 'movie' else meta.key_tv(tmdb_id)
    try:
        data = meta.get(key)[0]
    except Exception:
        data = None
    data = dict(data or fetch_tmdb_item_detail(media, tmdb_id, {}, addon) or {})
    if not data.get('overview') or not data.get('tagline'):
        english = fetch_tmdb_item_detail(media, tmdb_id, {'language': 'en-US'}, addon) or {}
        for field in ('overview', 'tagline'):
            data[field] = data.get(field) or english.get(field) or ''
    return data


class TitlePicker(xbmcgui.WindowXMLDialog):
    """Workers only prepare data and queue it; `apply()` in the script thread is the one that touches controls."""

    def __init__(self, *args, **kwargs):
        self.media = kwargs.pop('media')
        self.query = kwargs.pop('query')
        self.heading = kwargs.pop('heading')
        self.addon = kwargs.pop('addon')
        super().__init__(*args, **kwargs)
        self.results = []
        self.pending = []
        self.updates = queue.Queue()
        self.lock = threading.Lock()
        self.wake = threading.Condition(self.lock)
        self.ready = False
        self.closed = False
        self.touched = False
        self.picked = None

    def onInit(self):
        self.setProperty('picker.heading', self.heading)
        self.setProperty('picker.modern', '1' if family.style() == 'Modern' else '')
        self.setProperty('picker.status', self.addon.getLocalizedString(S_SEARCHING).format(self.query))
        self.list = self.getControl(LIST)
        if not self.ready:
            self.setFocusId(9001)
            self.ready = True
            threading.Thread(target=self._search, daemon=True).start()
            for _ in range(WORKERS):
                threading.Thread(target=self._details, daemon=True).start()

    def apply(self):
        """Put what the workers prepared on screen."""
        if not self.ready:
            return
        while not self.closed:
            try:
                kind, value = self.updates.get_nowait()
            except queue.Empty:
                return
            if kind == 'status':
                self.setProperty('picker.status', value)
            elif kind == 'items':
                first = self.list.size() == 0
                self.list.addItems(value)
                if first and not self.touched:
                    self.setFocusId(LIST)
            elif kind == 'details':
                index, props = value
                item = self.list.getListItem(index)
                for name, text in props.items():
                    item.setProperty(name, text)

    # --- background -----------------------------------------------------------------------------------------
    def _not_found(self):
        self.updates.put(('status', self.addon.getLocalizedString(30153 if self.media == 'movie' else 30148)))

    def _search(self):
        page, pages = 1, 1
        while page <= min(pages, PAGES) and not self.closed:
            try:
                data = search(self.media, self.query, page, self.addon)
            except Exception as exc:
                xbmc.log('[Milionář] title search failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
                break
            pages = data.get('total_pages') or 1
            self._add(data.get('results') or [])
            page += 1
        if not self.results:
            self._not_found()

    def _add(self, results):
        if self.closed or not results:
            return
        items = []
        for result in results:
            item = xbmcgui.ListItem(_label(self.media, result), offscreen=True)
            if result.get('poster_path'):
                item.setArt({'poster': POSTER + result['poster_path']})
            item.setProperty('meta', _meta(self.media, result, {}))
            item.setProperty('rating', _rating(result))
            item.setProperty('plot', result.get('overview') or '')
            items.append(item)
        with self.lock:
            start = len(self.results)
            self.results.extend(results)
            self.updates.put(('items', items))
            self.pending.extend(range(start, len(self.results)))
            self.wake.notify_all()

    def _details(self):
        while True:
            with self.lock:
                while not self.pending and not self.closed:
                    self.wake.wait(0.5)
                if self.closed:
                    return
                index = self.pending.pop(0)
                result = self.results[index]
            try:
                data = details(self.media, result['id'], self.addon)
            except Exception as exc:
                xbmc.log('[Milionář] title details failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
                continue
            self.updates.put(('details', (index, {
                'meta': _meta(self.media, result, data),
                'genres': ' · '.join(g.get('name', '') for g in data.get('genres') or [] if g.get('name')),
                'tagline': (data.get('tagline') or '').strip(),
                'plot': data.get('overview') or result.get('overview') or ''})))

    def _prioritize(self):
        """The focused title and its neighbours load next."""
        index = self.list.getSelectedPosition()
        with self.lock:
            for near in (index + 1, index - 1, index):
                if near in self.pending:
                    self.pending.remove(near)
                    self.pending.insert(0, near)

    # --- input ----------------------------------------------------------------------------------------------
    def stop(self):
        with self.lock:
            self.closed = True
            self.wake.notify_all()

    def onAction(self, action):
        if action.getId() in BACK:
            self.stop()
            return
        self.touched = True
        if self.getFocusId() == LIST:
            self._prioritize()

    def onClick(self, control_id):
        if control_id == LIST:
            index = self.list.getSelectedPosition()
            if 0 <= index < len(self.results):
                self.picked = self.results[index]
                self.stop()
        elif control_id == CANCEL:
            self.stop()


def pick(media, query, heading, addon):
    """The chosen TMDb search result (dict) or None; `media` is 'movie' or 'tv'.

    show() + a short loop instead of doModal(): the loop is the script thread that applies the workers' results
    while Kodi delivers onAction/onClick to it between the waits."""
    if not family.active():
        return _plain_pick(media, query, heading, addon)
    dialog = TitlePicker(XML, addon.getAddonInfo('path'), 'Default', '1080i',
                         media=media, query=query, heading=heading, addon=addon)
    monitor = xbmc.Monitor()
    try:
        dialog.show()
        while not dialog.closed and not monitor.waitForAbort(0.03):
            dialog.apply()
        return dialog.picked
    finally:
        dialog.stop()
        dialog.close()
        del dialog


def _plain_pick(media, query, heading, addon):
    """Another skin: the search first, then Kodi's own select (the former behaviour)."""
    results = search(media, query, 1, addon).get('results') or []
    if not results:
        xbmcgui.Dialog().notification(addon.getLocalizedString(30153 if media == 'movie' else 30148), query,
                                      xbmcgui.NOTIFICATION_INFO)
        return None
    index = xbmcgui.Dialog().select(heading, [_label(media, r) for r in results])
    return results[index] if index >= 0 else None
