# -*- coding: utf-8 -*-
"""Shared item menus. Widget overrides keep their existing storage and inheritance."""
import json

import xbmcaddon

SETTING = 'context_menu_profiles'
# profile: (title, row whose configured menu seeds it, allowed actions)
PROFILES = {
    'movie': (32705, 'widget_tmdb_popular_movies', ('play', 'restart', 'source', 'detail', 'watched', 'list', 'hide_continue', 'channel', 'similar', 'collection', 'game', 'history', 'web')),
    'tv': (32706, 'widget_tmdb_popular_series', ('folder', 'next', 'next_source', 'detail', 'watched', 'list', 'channel', 'similar', 'game', 'history', 'web')),
    'season': (32707, 'my_series_added', ('open', 'folder', 'next', 'next_source', 'detail', 'watched', 'list', 'channel', 'similar', 'game', 'web')),
    'episode': (32708, 'cont_series', ('play', 'restart', 'source', 'detail', 'folder', 'season', 'next', 'watched', 'list', 'hide_continue', 'channel', 'similar', 'game', 'history', 'web')),
    'person': (32709, '', ('detail', 'open', 'favorite', 'remove_favorite', 'game')),
    'folder': (32710, '', ('open', 'web')),
    'action': (32711, '', ('open', 'game', 'history', 'web')),
    'file': (32712, '', ('play', 'best', 'file_info', 'download', 'download_pick', 'autoplay')),
    'channel_tv': (32713, 'widget_mytv_channels', ('live', 'open', 'live_shuffle', 'first', 'random', 'edit_channel', 'rename_channel', 'move_channel', 'delete_channel')),
    'channel_cinema': (32714, 'widget_mycinema_channels', ('live', 'open', 'random', 'edit_channel', 'rename_channel', 'move_channel', 'delete_channel')),
    'channel_movie': (32715, 'widget_mycinema_recommended', ('play', 'detail', 'list', 'channel', 'similar', 'collection', 'game', 'channel_open', 'edit_progress', 'remove_program', 'move_program')),
    'channel_tvshow': (32716, 'my_series_added', ('next', 'folder', 'detail', 'list', 'channel', 'similar', 'game', 'channel_open', 'edit_progress', 'remove_program', 'move_program')),
    'channel_episode': (32717, 'widget_mytv_next', ('play', 'detail', 'folder', 'season', 'list', 'channel', 'similar', 'game', 'channel_open', 'edit_progress', 'remove_program', 'move_program')),
    'vinyl_song': (32718, 'vinyl_favorite_songs', ('play', 'play_from', 'queue', 'favorite', 'add_playlist', 'create_playlist', 'remove_song', 'album', 'artist', 'song_up', 'song_down')),
    'vinyl_playlist': (32719, 'vinyl_playlists', ('open', 'play_all', 'shuffle', 'queue', 'favorite', 'create_playlist', 'rename_playlist', 'delete_playlist')),
    'vinyl_album': (32720, 'vinyl_curator', ('open', 'play_all', 'shuffle', 'queue', 'favorite', 'create_playlist')),
    'vinyl_artist': (32721, 'vinyl_artists', ('open', 'play_all', 'shuffle', 'queue', 'favorite', 'create_playlist')),
    'vinyl_genre': (32722, 'vinyl_genres', ('open', 'play_all', 'shuffle', 'queue', 'create_playlist')),
    'vinyl_radio': (32723, 'vinyl_radios', ('open', 'play_all', 'queue', 'create_playlist')),
}


def key(data):
    kind = data.get('type', 'action')
    if kind == 'vinyl':
        return 'vinyl_' + data.get('kind', 'song')
    if kind == 'channel':
        return 'channel_' + data.get('kind', 'tv')
    if data.get('channel_id'):
        return 'channel_' + ('tvshow' if kind in ('tv', 'season') else kind)
    return kind if kind in PROFILES else 'action'


def catalog(row):
    profile = row.split(':', 1)[1]
    actions = PROFILES[profile][2]
    if profile in ('movie', 'channel_movie'):
        return actions + ('plot', 'trailer', 'director')
    if profile in ('tv', 'season', 'episode', 'channel_tvshow', 'channel_episode'):
        return actions + ('plot', 'trailer', 'creators')
    return actions


def _seed(profile, current=False):
    from wcs.skin import defaults, slots
    row = PROFILES[profile][1]
    if current and row:
        for sec in slots.SECTIONS:
            for n in range(1, slots.SLOTS + 1):
                widget = slots.current(sec, n)
                if widget['type'] == row and widget.get('menu') is not None:
                    return widget['menu'], True
    shipped = defaults.load()
    menu = shipped.get(SETTING, {}).get(profile)
    if menu is not None:
        return menu, False
    for section in shipped.get('sections', {}).values():
        for widget in section.get('widgets', []):
            if widget['type'] == row and widget.get('menu') is not None:
                return widget['menu'], True
    return None, False


def defaults(row, current=False):
    from wcs.skin import context
    profile = row.split(':', 1)[1]
    seed, from_widget = _seed(profile, current)
    if seed is None:
        source = PROFILES[profile][1]
        if source:
            seed = context.defaults(source)
            from_widget = True
        else:
            primary = {'person': ('detail', 'open', 'favorite'), 'folder': ('open',),
                       'action': ('open',), 'file': ('play', 'best', 'download')}.get(profile, ())
            seed = {'main': list(primary), 'more': [], 'hidden': []}
    if profile == 'season' and from_widget:
        # The series' primary navigation becomes opening this season; the parent series stays in More.
        seed = {group: ['open' if action == 'folder' else action for action in values]
                for group, values in seed.items()}
    # Every applicable action appears exactly once, with the supplied order and hidden choices intact.
    return context.normalize(row, seed)


def _read():
    try:
        value = json.loads(xbmcaddon.Addon('plugin.video.milionar').getSetting(SETTING) or '{}')
        return value if isinstance(value, dict) else {}
    except ValueError:
        return {}


def config(profile):
    from wcs.skin import context
    saved = _read()
    row = 'shared:' + profile
    if profile not in saved:
        saved[profile] = defaults(row, current=True)
        _write(saved)
    return context.normalize(row, saved[profile])


def _write(saved):
    xbmcaddon.Addon('plugin.video.milionar').setSetting(SETTING, json.dumps(saved, separators=(',', ':')))


def edit(profile):
    if profile not in PROFILES:
        return
    from wcs.skin import context, context_dialogs
    result = context_dialogs.edit('shared:' + profile, config(profile),
                                  title=context.text(32703).format(context.text(PROFILES[profile][0])))
    if result is not None:
        saved = _read()
        saved[profile] = result
        _write(saved)
