# -*- coding: utf-8 -*-
"""The Radio Studio card (docs/plan/vinyl-radio/020): every way to the Vinyl radio in one dialog.

A modal card in the look of the Millionaire game (vinyl/DialogVinylRadioStudio.xml, generated by
scripts/game_dialog/gen_radio_studio.py). Pages: what is on air, the user's playlists, "Nové vysílání" (music style and
period), the recordings; then the start of the chosen source, which is Vinyl's Studio lobby: on the left "Spustit
vysílání", "Spustit teď — {show of the time of day}" and the moderators (OK picks one, it never starts), on the right
every setting of the lobby (radio_start.rows). The dialog only chooses: `show()` returns what to do and
wcs/vinyl/radio.py does it once the card is closed (a stream never starts under a modal window).
"""
import xbmc
import xbmcaddon
import xbmcgui

from wcs.vinyl import client, radio_start

XML = 'vinyl/DialogVinylRadioStudio.xml'
ACTION_PREVIOUS_MENU, ACTION_NAV_BACK = 10, 92
PAGE_CONTROLS = {9701: 'live', 9702: 'playlists', 9703: 'create', 9704: 'records'}
TAB_CONTROL = {page: control for control, page in PAGE_CONTROLS.items()}
CLOSE, LIST, SETTINGS, MODERATORS, START, QUICK, START_SETTINGS = 9709, 9720, 9730, 9740, 9750, 9752, 9760
HEADINGS = {'live': (33101, 33152), 'playlists': (33145, 33150), 'create': (33103, 33151), 'records': (33104, 33153)}
EMPTY = {'live': 33124, 'playlists': 33159, 'records': 33135}


def text(number):
    return client.addon().getLocalizedString(number)


def _log(message, level=xbmc.LOGINFO):
    xbmc.log('[Milionář Vinyl Radio] studio: {}'.format(message), level)


def show(page='live', source=None):
    """Open the card on `page` (or on the start of `source`) and return the decision:
    ('tune', broadcast id) | ('control', op, broadcast id) | ('session', session id) |
    ('launch', payload, characterId, page) | None."""
    window = Studio(XML, xbmcaddon.Addon().getAddonInfo('path'), 'Default', '1080i')
    window.first, window.source = page, source
    window.doModal()
    decision = window.decision
    del window
    _log('decision {}'.format(decision[0] if decision else None))
    return decision


def source_of_playlist(playlist):
    """The start of a playlist of the user's own (its Studio page is the playlist)."""
    identity = int(playlist['id'])
    return {'kicker': text(33145), 'title': playlist.get('name') or '', 'count': playlist.get('song_count') or 0,
            'payload': {'playlistId': identity}, 'page': {'pageType': 'playlist', 'pageId': str(identity)},
            'art': client.cover(playlist, 'playlist'), 'back': 'playlists'}


def source_of_create(style, period):
    return {'kicker': text(33103), 'title': style, 'count': 0, 'payload': {'create': {'musicStyle': style, 'timePeriod': period}},
            'page': radio_start.CREATE_PAGE, 'art': '', 'back': 'create'}


class Studio(xbmcgui.WindowXMLDialog):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.first, self.source = 'live', None
        self.page, self.rows, self.keys = 'live', [], []
        self.opts, self.prefs, self.dram, self.moderators = None, {}, None, []
        self.decision = None
        self.ready = False                                  # Kodi focuses the default control before onInit
        self.busy = False                                   # keys pressed while a page loads change nothing
        self.last_focus = 0

    # ---- life
    def onInit(self):
        title = text(33147).upper()
        self.setProperty('VinylRadio.TitleSpaced', '  '.join(' '.join(word) for word in title.split()))
        if self.source:
            self._guarded(self._start, self.source)
        else:
            page = self.first if self.first in TAB_CONTROL else 'live'
            self._page(page)
            self._focus(TAB_CONTROL[page])
            self._guarded(self._show, page)
        self.ready = True

    def onAction(self, action):
        if action.getId() in (ACTION_PREVIOUS_MENU, ACTION_NAV_BACK):
            if self.busy:
                return
            if self.page == 'start' and self.source.get('back'):
                self._guarded(self._show, self.source['back'])
                self._focus(SETTINGS if self.page == 'create' else LIST)      # filled first: an empty list takes no focus
            else:
                self.close()
            return
        super().onAction(action)

    def onFocus(self, control_id):
        # the pages follow the focus moving inside the left column; arriving there from a page changes nothing
        moved = self.last_focus in PAGE_CONTROLS or self.last_focus == CLOSE
        self.last_focus = control_id
        if self.ready and not self.busy and moved and control_id in PAGE_CONTROLS and PAGE_CONTROLS[control_id] != self.page:
            self._guarded(self._show, PAGE_CONTROLS[control_id])

    def onClick(self, control_id):
        if self.busy:
            _log('click {} ignored while loading'.format(control_id))
            return
        self._guarded(self._click, control_id)

    def _guarded(self, step, *args):
        """Run a step that talks to Vinyl; a failure is shown, never left as a stuck card."""
        try:
            step(*args)
        except client.LoginRequired:
            xbmcgui.Dialog().notification('Vinyl', text(32518), xbmcgui.NOTIFICATION_ERROR)
        except Exception as exc:
            _log('{} failed: {}: {}'.format(step.__name__, type(exc).__name__, exc), xbmc.LOGWARNING)
            xbmcgui.Dialog().notification('Vinyl', text(33131).format(exc), xbmcgui.NOTIFICATION_ERROR)
        finally:
            self._busy(False)

    def _click(self, control_id):
        if control_id == CLOSE:
            self.close()
        elif control_id == LIST:
            self._pick(self.getControl(LIST).getSelectedPosition())
        elif control_id == SETTINGS:
            self._create_setting(self.getControl(SETTINGS).getSelectedPosition())
        elif control_id == START:
            self._launch(radio_start.current(self.opts, self.prefs)['id'])
        elif control_id == QUICK:
            self._launch(self.opts['recommended']['characterId'])
        elif control_id == MODERATORS:
            self._moderator(self.getControl(MODERATORS).getSelectedPosition())
        elif control_id == START_SETTINGS:
            self._setting(self.getControl(START_SETTINGS).getSelectedPosition())
        elif control_id in PAGE_CONTROLS:
            self._show(PAGE_CONTROLS[control_id])

    def _focus(self, control_id):
        """Focus a control of the page just shown: Kodi shows it a frame later, and focusing a hidden control would
        fall back to the default one."""
        monitor = xbmc.Monitor()
        for _ in range(50):
            if xbmc.getCondVisibility('Control.IsVisible({})'.format(control_id)) or monitor.waitForAbort(0.02):
                break
        self.setFocusId(control_id)

    def _finish(self, decision):
        self.decision = decision
        self.close()

    # ---- the pages
    def _page(self, page, tab=None):
        self.page = page
        self.setProperty('VinylRadio.Page', page)
        self.setProperty('VinylRadio.Tab', tab if tab is not None else page)
        heading, lead = HEADINGS.get(page, (0, 0))
        self.setProperty('VinylRadio.Heading', text(heading) if heading else '')
        self.setProperty('VinylRadio.Lead', text(lead) if lead else '')
        self.setProperty('VinylRadio.Empty', '')

    def _busy(self, on):
        self.busy = on
        self.setProperty('VinylRadio.Busy', '1' if on else '')

    def _show(self, page):
        self._page(page)
        self.rows = []
        self._fill(LIST, [])
        self._busy(True)
        if page == 'live':
            self.rows = client.request('radio/broadcast', authenticated=False, timeout=(3, 10))['broadcasts']
            self._fill(LIST, [self._broadcast_row(b) for b in self.rows])
        elif page == 'playlists':
            if not client.account():
                raise client.LoginRequired()
            # the Home row's cache has them all (wcs/vinyl/widgets.py); the network only when it is not there yet
            self.rows = [p for p in client.cached('playlists') if p.get('id')] or client.sources(['playlists'])['playlists']
            self._fill(LIST, [self._playlist_row(p) for p in self.rows])
        elif page == 'records':
            self.rows = [s for s in client.request('radio/sessions/all')['sessions'] if s.get('recording_file')]
            self._fill(LIST, [self._record_row(s) for s in self.rows])
        elif page == 'create':
            self._create_rows()
        if page in EMPTY and not self.rows:
            self.setProperty('VinylRadio.Empty', text(EMPTY[page]))
        _log('page {} ({} rows)'.format(page, len(self.rows) if page in EMPTY else '-'))

    def _fill(self, list_id, items, position=None):
        control = self.getControl(list_id)
        control.reset()
        control.addItems(items)
        if position is not None and items:
            control.selectItem(min(max(position, 0), len(items) - 1))

    @staticmethod
    def _row(c1, c2='', c3='', c4='', art=''):
        li = xbmcgui.ListItem(c1, offscreen=True)
        for key, value in (('c1', c1), ('c2', c2), ('c3', c3), ('c4', c4)):
            li.setProperty(key, str(value or ''))
        if art:
            li.setArt({'thumb': art})
        return li

    def _broadcast_row(self, broadcast):
        from wcs.vinyl import radio
        now = broadcast.get('nowPlaying') or {}
        return self._row(broadcast.get('title') or text(33100), radio.song_line(now) or text(33139),
                         text(33163) if radio.mine(broadcast) else text(33143), text(33132).format(broadcast.get('listeners') or 0),
                         client.cover(now, 'song') if now.get('id') else 'DefaultAddonMusic.png')

    def _playlist_row(self, playlist):
        from wcs.vinyl import presentation
        return self._row(playlist.get('name') or '', playlist.get('description') or '',
                         presentation.tracks(playlist.get('song_count') or 0), '', client.cover(playlist, 'playlist'))

    def _record_row(self, session):
        from wcs.vinyl import presentation
        names = ' & '.join(n for n in (session.get('moderator_name'), session.get('moderator_name_2')) if n)
        length = presentation.duration(session.get('recording_duration')) if session.get('recording_duration') else ''
        return self._row(session.get('title') or session.get('playlist_name') or text(33144), names, length,
                         presentation.created(session.get('created_at')), client.cover(session, 'radio'))

    def _pick(self, position):
        if not 0 <= position < len(self.rows):
            return
        entry = self.rows[position]
        if self.page == 'live':
            from wcs.vinyl import radio
            if radio.mine(entry):
                choice = xbmcgui.Dialog().select(entry.get('title') or text(33100), [text(33146), text(33125), text(33126)])
                if choice < 0:
                    return
                if choice > 0:
                    self._finish(('control', 'skip' if choice == 1 else 'stop', entry['id']))
                    return
            self._finish(('tune', entry['id']))
        elif self.page == 'records':
            self._finish(('session', entry['id']))
        elif self.page == 'playlists':
            self._start(source_of_playlist(entry))

    # ---- Nové vysílání: the music style and the period
    def _create_rows(self, position=None):
        self.opts = radio_start.options(radio_start.CREATE_PAGE)
        self.prefs = dict(self.opts['prefs'])
        periods = self.opts['periods']
        period = self.prefs.get('createRadioTimePeriod') or 'auto'
        label = next((p['label'] for p in periods if p['value'] == period), period)
        self.keys = ['style', 'period', 'next']
        self._fill(SETTINGS, [self._row(text(33120), self.prefs.get('createRadioMusicStyle') or '—'),
                              self._row(text(33121), label), self._start_row(text(33158))], position)

    @staticmethod
    def _start_row(label):
        li = Studio._row(label)
        li.setProperty('start', 'true')
        return li

    def _create_setting(self, position):
        if not 0 <= position < len(self.keys):
            return
        key, page, dialog = self.keys[position], radio_start.CREATE_PAGE, xbmcgui.Dialog()
        if key == 'style':
            value = dialog.input(text(33120), self.prefs.get('createRadioMusicStyle') or '')
            if value is not None and value.strip():
                radio_start.save(page, {'createRadioMusicStyle': value.strip()})
        elif key == 'period':
            periods = self.opts['periods']
            saved = self.prefs.get('createRadioTimePeriod') or 'auto'
            picked = dialog.select(text(33121), [p['label'] for p in periods],
                                   preselect=next((i for i, p in enumerate(periods) if p['value'] == saved), 0))
            if picked >= 0:
                radio_start.save(page, {'createRadioTimePeriod': periods[picked]['value']})
        else:
            style = (self.prefs.get('createRadioMusicStyle') or '').strip()
            if not style:
                dialog.notification('Vinyl', text(33162))
                return
            self._start(source_of_create(style, self.prefs.get('createRadioTimePeriod') or 'auto'))
            return
        self._busy(True)
        self._create_rows(position)

    # ---- the start of a source: Vinyl's Studio lobby
    def _start(self, source):
        self.source = source
        self._page('start', tab=source.get('back') or '')
        self._busy(True)
        self.opts = radio_start.options(source['page'])
        self.prefs = dict(self.opts['prefs'])
        self.dram = radio_start.dramaturgy(source['page'])
        from wcs.skin import hero
        self.setProperty('VinylRadio.Kicker', source['kicker'].upper())
        self.setProperty('VinylRadio.Title', source['title'])
        self.setProperty('VinylRadio.Fanart', hero.blur(source.get('art') or ''))
        self.setProperty('VinylRadio.Note', text(33161).format(self.opts['recommended']['label']))
        self.setProperty('VinylRadio.QuickLabel', text(33105).format(self.opts['recommended']['label']))
        moderator = radio_start.current(self.opts, self.prefs)
        self._render(None, 0)
        self.getControl(MODERATORS).selectItem(next((i for i, c in enumerate(self.moderators) if c['id'] == moderator['id']), 0))
        self._busy(False)
        self._focus(START)
        _log('start of {}/{}: {} moderators, {} settings{}'.format(source['page']['pageType'], source['page']['pageId'],
                                                                    len(self.moderators), len(self.keys),
                                                                    ', dramaturgy' if self.dram else ''))

    def _render(self, moderators_at=None, settings_at=None):
        """The lobby as it is now: facts, the moderators (the saved one ringed) and the settings rows."""
        opts, prefs, source = self.opts, self.prefs, self.source
        mode = radio_start.mode_of(prefs)
        moderator = radio_start.current(opts, prefs)
        from wcs.vinyl import presentation
        facts = [presentation.tracks(source['count'])] if source.get('count') else []
        facts.append(radio_start.summary(opts, prefs, moderator))
        self.setProperty('VinylRadio.Facts', '  ·  '.join(facts))
        self.moderators = [c for c in opts['characters'] if c['id'] != radio_start.CUSTOM] + \
                          [c for c in opts['characters'] if c['id'] == radio_start.CUSTOM]
        cards = []
        for character in self.moderators:
            li = self._row(character['name'], radio_start.describe(character, mode))
            li.setProperty('current', 'true' if character['id'] == moderator['id'] else '')
            cards.append(li)
        self._fill(MODERATORS, cards, moderators_at)
        self.keys = []
        items = []
        for key, label, value in radio_start.rows(opts, prefs, self.dram):
            self.keys.append(key)
            items.append(self._row(label, value))
        self._fill(START_SETTINGS, items, settings_at)

    def _moderator(self, position):
        """OK on a moderator picks it (saved at once, its dramaturgy preset follows); it never starts."""
        if not 0 <= position < len(self.moderators):
            return
        picked = self.moderators[position]['id']
        if picked == radio_start.current(self.opts, self.prefs)['id']:
            return
        self._busy(True)
        radio_start.save(self.source['page'], {'radioCharacterId': picked})
        self.prefs['radioCharacterId'] = picked
        radio_start.follow_moderator(self.dram, picked, radio_start.mode_of(self.prefs), self.opts)
        self._render(position, self.getControl(START_SETTINGS).getSelectedPosition())

    def _setting(self, position):
        if not 0 <= position < len(self.keys):
            return
        key = self.keys[position]
        if key == 'dramaturgy':
            radio_start.change_dramaturgy(self.dram, xbmcgui.Dialog())
        else:
            updates = radio_start.change(key, self.opts, self.prefs, xbmcgui.Dialog())
            if not updates:
                return
            self._busy(True)
            radio_start.save(self.source['page'], updates)
            self.prefs.update(updates)
            if key == 'mode':
                radio_start.follow_moderator(self.dram, radio_start.current(self.opts, self.prefs)['id'],
                                             radio_start.mode_of(self.prefs), self.opts)
        self._render(self.getControl(MODERATORS).getSelectedPosition(), position)
        self._busy(False)
        self._focus(START_SETTINGS)

    def _launch(self, character_id):
        self._finish(('launch', self.source['payload'], character_id, self.source['page']))
