# -*- coding: utf-8 -*-
"""Canonical play URLs of the addon library (docs/plan/milionar-library/040 §2).

One fixed URL per movie / episode; fixed parameter order and no other
parameters, so Kodi's own per-URL state (bookmarks, playcount) maps to a title
and not to a source file. Options travel in a Window property, never in the URL.
"""
from urllib.parse import parse_qsl, urlsplit

ADDON_ID = 'plugin.video.milionar'
ACTION = 'mplay'
BASE = 'plugin://{}/'.format(ADDON_ID)


def add_url(kind):
    """The existing keyboard/search/add flow shared by native listings and Home."""
    action = 'tmdb_add_movie&new=1&add_to_my_movies=1' if kind == 'movies' else 'tmdb_add_series&new=1&add_to_my_series=1'
    return '{}?action={}'.format(BASE, action)


def movie_url(tmdb_id):
    return '{}?action={}&type=movie&tmdb={}'.format(BASE, ACTION, int(tmdb_id))


def episode_url(show_tmdb_id, season, episode):
    return '{}?action={}&type=episode&tmdb={}&s={}&e={}'.format(
        BASE, ACTION, int(show_tmdb_id), int(season), int(episode))


def parse(url):
    """Canonical URL -> {'type': 'movie', 'tmdb': 1} / {'type': 'episode', 'tmdb', 's', 'e'}; None for anything else."""
    try:
        parts = urlsplit(url)
        if parts.scheme != 'plugin' or parts.netloc != ADDON_ID:
            return None
        params = dict(parse_qsl(parts.query, keep_blank_values=True))
        if params.get('action') != ACTION:
            return None
        if params.get('type') == 'movie':
            return {'type': 'movie', 'tmdb': int(params['tmdb'])}
        if params.get('type') == 'episode':
            return {'type': 'episode', 'tmdb': int(params['tmdb']), 's': int(params['s']), 'e': int(params['e'])}
    except (KeyError, ValueError):
        return None
    return None


def canonical(info):
    """Inverse of parse() for a parsed dict."""
    if info['type'] == 'movie':
        return movie_url(info['tmdb'])
    return episode_url(info['tmdb'], info['s'], info['e'])
