# -*- coding: utf-8 -*-
"""The addon's own quick actions: one place that does them, whoever asks (docs/plan/skin-optimization, part E).

Starting the plugin costs a script start in Kodi before anything happens: tens of milliseconds on a desktop, seconds on a
weak box that is busy. These actions do not need it. `run()` does one of them exactly as the plugin call always did, and
is used by

  * main.py, when Kodi did start the plugin for it (other skins, the fallback of our skin),
  * the service, when the skin asks it directly (wcs/skin/commands.py: `NotifyAll(plugin.video.milionar,run:<builtin>)`),
  * a context menu, for the entry the user chose (wcs.skin.context.run_chosen), in the process that shows the menu.

Not here on purpose: listings and resolvers (they need Kodi's directory handle), and everything that opens one of the
addon's big dialogs or the game through wcs/router.py. Those stay plugin runs: their own process, their own modules.
"""
import xbmc
from wcs.skin import family

# vinyl_* and skin_detail_* are prefixes; these of them are listings
LISTINGS = ('vinyl_browse', 'vinyl_favorites', 'skin_detail_row')
ACTIONS = ('show_wcs_details', 'skin_accent', 'skin_context', 'skin_context_native', 'skin_hero', 'skin_channel_edit',
           'skin_widgets_refresh', 'ctx_mark', 'ctx_hide_continue', 'ctx_list', 'ctx_open', 'ctx_list_toggle',
           'ctx_mark_toggle', 'ctx_next', 'channel_play', 'skin_context_edit', 'skin_classic', 'skin_navigation_defaults',
           'skin_navigation_titles', 'skin_slots', 'skin_wm', 'skin_menu_item', 'skin_slots_defaults', 'skin_defaults',
           'foryou_rate', 'foryou_pick', 'foryou_build', 'foryou_mode', 'mplay_req', 'skin_update')


def handles(action):
    """True for an action run() does (show_wcs_details only in our skin: elsewhere it is the addon's own dialog)."""
    if action in LISTINGS:
        return False
    if action == 'show_wcs_details':
        return family.active()
    return action in ACTIONS or action.startswith(('vinyl_', 'skin_detail_'))


def run(params, handle=-1):
    """Do the action of `params`; False when it is not one of ours (the caller starts or continues the plugin)."""
    action = params.get('action', '')
    if not handles(action):
        return False
    if action.startswith('skin_detail_'):
        from wcs.skin import detail
        detail.run(handle, params)
    elif action == 'show_wcs_details':
        from wcs.skin import detail
        detail.open_detail(params)
    elif action == 'skin_accent':
        from wcs.skin.appearance import select_accent
        select_accent()
    elif action == 'skin_context':
        from wcs.skin.context import home_context
        home_context()
    elif action == 'skin_context_native':
        from wcs.skin.context import native_context
        native_context()
    elif action == 'skin_hero':
        # a hero button without a ready builtin, its More options popup or its editor (wcs/skin/hero_buttons.py)
        from wcs.skin import hero_buttons
        hero_buttons.run(params)
    elif action == 'skin_channel_edit':
        from wcs.skin import channel_actions
        channel_actions.run(params)
    elif action.startswith('vinyl_'):
        from wcs.vinyl import actions
        actions.run(handle, params)
    elif action == 'skin_widgets_refresh':
        import xbmcaddon
        import xbmcgui
        xbmcgui.Dialog().notification('Milionář', xbmcaddon.Addon('plugin.video.milionar').getLocalizedString(32535))
        xbmcgui.Window(10000).setProperty('milionar.widgets.refreshing', '1')
        xbmc.executebuiltin('NotifyAll(plugin.video.milionar,skin_widgets_refresh)')
    elif action.startswith('ctx_'):
        from wcs.library2 import ctx
        ctx.run(params)
    elif action == 'channel_play':
        # a click on a MyTV / MyCinema channel of the Home widgets: start the channel without its dialog (150)
        from wcs.ai import channel_play
        channel_play.run(params)
    elif action == 'skin_context_edit':
        from wcs.skin.context import edit_menu
        edit_menu(params)
    elif action in ('skin_classic', 'skin_navigation_defaults', 'skin_navigation_titles'):
        from wcs.skin import navigation
        if action == 'skin_navigation_defaults':
            navigation.migrate()
        elif action == 'skin_navigation_titles':
            navigation.repair_titles()
        else:
            navigation.run(params)
    elif action in ('skin_slots', 'skin_wm', 'skin_menu_item', 'skin_slots_defaults', 'skin_defaults'):
        from wcs.skin import slots
        slots.run(params)
    elif action in ('foryou_rate', 'foryou_pick'):
        # Pro tebe feedback: rate a title, the first-run pick of favourites (docs/plan/pro-tebe/040)
        from wcs.foryou import feedback
        feedback.run(params)
    elif action == 'foryou_mode':
        # Pro tebe: Zobrazit: Vše / Filmy / Seriály (the hero button and the card's context menu)
        from wcs.foryou import mode
        mode.choose(params)
    elif action == 'foryou_build':
        # Pro tebe: rebuild the recommendations now (empty-state button; docs/plan/pro-tebe/030)
        from wcs.foryou import service as foryou_service
        foryou_service.manual(params)
    elif action == 'skin_update':
        # the settings menu's "Zkontrolovat aktualizace": window 1124 (docs/plan/skin-milionar/250-update.md)
        from wcs.skin import update
        update.run(params)
    elif action == 'mplay_req':
        from wcs.library2 import play, urls
        canonical = (urls.movie_url(params['tmdb']) if params.get('type') == 'movie' else
                     urls.episode_url(params['tmdb'], params['s'], params['e']))
        play.request(canonical, params.get('src', 'dialog'), params.get('from', 'start'))
    from wcs.skin import perflog                      # temporary timing line (docs/plan/skin-optimization)
    perflog.log('action {} done'.format(action))
    return True
