# -*- coding: utf-8 -*-
"""Start a tracked play: options in a Window property, Kodi always plays the canonical URL (020 §3, 040 §2)."""
import json
import time

import xbmc
import xbmcgui

from wcs.library2 import urls

REQUEST_PROPERTY = 'milionar.play_req'
REQUEST_MAX_AGE_S = 15
NP_PROPERTY = 'milionar.np'
ORIGIN_CHANNEL = 'channel'             # a MyTV / MyCinema play in the shared mode (wcs/library2/shared.py)


def request(canonical, src='dialog', start='start', close_dialogs=True, pick=None, origin=None, follow=True):
    """Ask Kodi to play `canonical` with options.

    src: dialog (source dialog / the existing autoplay settings) | auto (best automatic pick) | last (same file as before)
    start: resume (from the saved position) | start (from the beginning)
    pick: a source the caller already chose, {'ident', 'name', 'provider'}; the resolver then shows no dialog
    origin: ORIGIN_CHANNEL for a play started from a channel; follow: False when the library must not start what
    comes next (the channel has its own program)
    """
    payload = {'canonical': canonical, 'src': src, 'from': start, 'ts': time.time()}
    if pick:
        payload['pick'] = {k: pick.get(k) for k in ('ident', 'name', 'provider') if pick.get(k)}
    if origin:
        payload['origin'] = origin
    if not follow:
        payload['follow'] = False
    xbmcgui.Window(10000).setProperty(REQUEST_PROPERTY, json.dumps(payload))
    if close_dialogs:
        xbmc.executebuiltin('Dialog.Close(all, true)')
    xbmc.executebuiltin('PlayMedia({},{})'.format(canonical, 'resume' if start == 'resume' else 'noresume'))


def prepare(canonical, src='auto', start='start', max_age=REQUEST_MAX_AGE_S):
    """Store a request for an item that will be resolved later (autoplay queue): valid for `max_age` seconds."""
    payload = {'canonical': canonical, 'src': src, 'from': start, 'ts': time.time(), 'max_age': max_age}
    xbmcgui.Window(10000).setProperty(REQUEST_PROPERTY, json.dumps(payload))


def play_movie(tmdb_id, src='dialog', start='start', pick=None, origin=None, follow=True):
    request(urls.movie_url(tmdb_id), src, start, pick=pick, origin=origin, follow=follow)


def play_episode(show_id, season, episode, src='dialog', start='start', pick=None, origin=None, follow=True):
    request(urls.episode_url(show_id, season, episode), src, start, pick=pick, origin=origin, follow=follow)


def contract(info, stream, selected, canonical=None, title='', show_title='', runtime_s=0, start_at=0.0,
             origin='mplay', follow=True):
    """Write the now-playing contract the service tracker pairs with the stream Kodi starts (040 §2).

    info: {'type': 'movie' | 'episode', 'tmdb', 's', 'e'}; selected: the picked file {'ident', 'provider', 'name'}.
    """
    canonical = canonical or (urls.movie_url(info['tmdb']) if info['type'] == 'movie'
                              else urls.episode_url(info['tmdb'], info['s'], info['e']))
    selected = selected or {}
    data = {'token': '{}-{}'.format(canonical, int(time.time() * 1000)), 'type': info['type'], 'tmdb': int(info['tmdb']),
            's': info.get('s'), 'e': info.get('e'), 'title': title, 'show_title': show_title,
            'stream_url': stream, 'ident': selected.get('ident'), 'provider': selected.get('provider', 'webshare'),
            'file_name': selected.get('name', ''), 'start_at': start_at, 'origin': origin, 'ts': time.time(),
            'runtime_s': int(runtime_s or 0)}
    if not follow:
        data['follow'] = False
    xbmcgui.Window(10000).setProperty(NP_PROPERTY, json.dumps(data))
    return data


def consume(canonical):
    """The pending request for this canonical URL (and clear it), or defaults. Stale or foreign requests are ignored."""
    window = xbmcgui.Window(10000)
    raw = window.getProperty(REQUEST_PROPERTY)
    result = {'src': 'dialog', 'from': 'start', 'pick': None}
    if raw:
        try:
            data = json.loads(raw)
            if data.get('canonical') == canonical and time.time() - data.get('ts', 0) <= data.get('max_age', REQUEST_MAX_AGE_S):
                result = {'src': data.get('src', 'dialog'), 'from': data.get('from', 'start'), 'pick': data.get('pick')}
                result.update({key: data[key] for key in ('origin', 'follow') if key in data})   # a channel's play
                window.clearProperty(REQUEST_PROPERTY)
        except ValueError:
            window.clearProperty(REQUEST_PROPERTY)
    return result
