# -*- coding: utf-8 -*-
"""Vinyl radio (docs/plan/vinyl-radio): what is on air, starting a broadcast, recordings, the creator's controls.

The radio runs on the Vinyl server; Kodi plays one MP3 stream (or a recording) and the service
(wcs/vinyl/radio_player.py) shows in the player what is heard. Every start is chosen in the Radio Studio card
(wcs/vinyl/radio_studio.py, docs/plan/vinyl-radio/020) and goes through Vinyl's own server start (`POST radio/launch`)
with the user's saved Studio choices (wcs/vinyl/radio_start.py).
"""
import os
import random
import uuid
from urllib.parse import urlencode

import xbmc
import xbmcgui
import xbmcplugin

from wcs.vinyl import client

BASE = 'plugin://plugin.video.milionar/'
SAMPLE = 50                       # a collection airs from a shadow playlist of at most 50 random songs (as on the web)


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


def _url(**params):
    return BASE + '?' + urlencode(params)


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


def listener_id():
    """This Kodi's stable id in the broadcast's listener list; not a secret."""
    path = os.path.join(client.PROFILE, 'vinyl_radio_listener')
    try:
        with open(path, encoding='utf-8') as handle:
            value = handle.read().strip()
        if value:
            return value
    except OSError:
        pass
    value = 'kodi-' + uuid.uuid4().hex[:8]
    try:
        os.makedirs(client.PROFILE, exist_ok=True)
        with open(path, 'w', encoding='utf-8') as handle:
            handle.write(value)
    except OSError:
        pass
    return value


def song_line(song):
    return ' – '.join(p for p in ((song or {}).get('artist'), (song or {}).get('title')) if p)


def hosts(broadcast):
    names = broadcast.get('hosts') or {}
    return ' & '.join(n for n in (names.get('name'), names.get('name2')) if n)


def _audio(li, path, endless=False):
    li.setProperty('IsPlayable', 'true')
    li.setMimeType('audio/mpeg')
    if endless:
        li.setContentLookup(False)                  # no HEAD request: a live stream never ends
    # A recording keeps the lookup: without it Kodi does not learn the file can be seeked.
    return path, li


def broadcast_item(broadcast):
    """The playable stream of a broadcast on air, labelled with what it plays now."""
    now = broadcast.get('nowPlaying') or {}
    path = client.stream('radio/broadcast/{}/stream?{}'.format(broadcast['id'], urlencode({'listener': listener_id()})))
    li = xbmcgui.ListItem(broadcast.get('title') or text(33100), text(33128).format(song_line(now)) if now else text(33139),
                          path=path, offscreen=True)
    tag = li.getMusicInfoTag()
    tag.setTitle(now.get('title') or broadcast.get('title') or '')
    tag.setArtist(now.get('artist') or hosts(broadcast) or broadcast.get('creatorName') or '')
    tag.setAlbum(broadcast.get('title') or '')
    tag.setComment(' · '.join(p for p in (hosts(broadcast), broadcast.get('creatorName'),
                                         text(33132).format(broadcast.get('listeners') or 0)) if p))
    tag.setMediaType('song')
    art = client.cover(now, 'song') if now.get('id') else 'DefaultMusicAlbums.png'
    li.setArt({'thumb': art, 'icon': art, 'fanart': art})
    return _audio(li, path, endless=True)


def mine(broadcast):
    return str(broadcast.get('creatorUserId')) == str(client.account())


def controls(broadcast):
    """The creator's rows under their broadcast: plain items, so no context menu has to carry them."""
    return [_entry(text(label), _url(action='vinyl_radio_control', op=op, id=broadcast['id']), False, icon)
            for op, label, icon in (('skip', 33125, 'DefaultMusicSongs.png'), ('stop', 33126, 'DefaultIconError.png'))]


def recording_item(session):
    path = client.stream('radio/broadcast/recording/{}'.format(int(session['id'])))
    title = session.get('title') or session.get('playlist_name') or text(33144)
    names = ' & '.join(n for n in (session.get('moderator_name'), session.get('moderator_name_2')) if n)
    from wcs.vinyl import presentation
    li = xbmcgui.ListItem(title, ' · '.join(p for p in (names, presentation.created(session.get('created_at'))) if p),
                          path=path, offscreen=True)
    tag = li.getMusicInfoTag()
    tag.setTitle(title)
    tag.setArtist(names)
    tag.setAlbum(title)
    tag.setDuration(int(session.get('recording_duration') or 0))
    tag.setMediaType('song')
    art = client.cover(session, 'radio')
    li.setArt({'thumb': art, 'icon': art, 'fanart': art})
    return _audio(li, path)


def _folder(handle, items, content='songs'):
    xbmcplugin.setContent(handle, content)
    xbmcplugin.addDirectoryItems(handle, items, len(items))
    xbmcplugin.endOfDirectory(handle, cacheToDisc=False)


def _entry(label, path, folder, icon='DefaultMusicAlbums.png', label2=''):
    li = xbmcgui.ListItem(label, label2, path=path, offscreen=True)
    li.setArt({'icon': icon, 'thumb': icon})
    return path, li, folder


def root(handle):
    items = [_entry(text(33147), _url(action='vinyl_radio_studio'), False, 'DefaultAddonProgram.png'),
             _entry(text(33101), _url(action='vinyl_radio_live'), True, 'DefaultAddonMusic.png'),
             _entry(text(33102), _url(action='vinyl_radio_playlists'), True, 'DefaultMusicPlaylists.png'),
             _entry(text(33103), _url(action='vinyl_radio_create'), False, 'DefaultAddSource.png'),
             _entry(text(33104), _url(action='vinyl_radio_records'), True, 'DefaultMusicRecentlyPlayed.png')]
    _folder(handle, items, 'files')


def live(handle):
    broadcasts = client.request('radio/broadcast', authenticated=False)['broadcasts']
    _log('on air: {}'.format(len(broadcasts)))
    items = []
    for broadcast in broadcasts:
        items.append(broadcast_item(broadcast) + (False,))
        if mine(broadcast):
            items += controls(broadcast)
    if not items:
        items = [_entry(text(33124), _url(action='vinyl_radio_live'), True, 'DefaultIconInfo.png')]
    _folder(handle, items)


def playlists(handle):
    if not client.account():
        raise client.LoginRequired()
    entries = client.sources(['playlists'])['playlists']
    items = []
    for playlist in entries:
        path = _url(action='vinyl_radio_start', kind='playlist', id=playlist['id'], name=playlist.get('name', ''))
        from wcs.vinyl import presentation
        li = xbmcgui.ListItem(playlist.get('name', ''), presentation.tracks(playlist.get('song_count') or 0), path=path, offscreen=True)
        art = client.cover(playlist, 'playlist')
        li.setArt({'thumb': art, 'icon': art})
        items.append((path, li, False))
    _folder(handle, items, 'albums')


def records(handle):
    sessions = client.request('radio/sessions/all')['sessions']
    items = []
    for session in sessions:
        if session.get('recording_file'):
            items.append(recording_item(session) + (False,))
        elif session.get('mode') == 'pregenerated' and int(session.get('event_count') or 0) > 0:
            # Prepared ahead in the browser: the server can air it and record it (D18).
            path = _url(action='vinyl_radio_session', id=session['id'])
            items.append(_entry(session.get('playlist_name') or text(33144), path, False, client.cover(session, 'radio'), text(33129)))
    if not items:
        items = [_entry(text(33135), _url(action='vinyl_radio_records'), True, 'DefaultIconInfo.png')]
    _folder(handle, items)


def tune(broadcast):
    path, li = broadcast_item(broadcast)
    _log('tuning in to {} ({})'.format(broadcast['id'], broadcast.get('title')))
    xbmc.Player().play(path, li)


def _busy(on):
    xbmc.executebuiltin('ActivateWindow(busydialognocancel)' if on else 'Dialog.Close(busydialognocancel)')


def _status(exc):
    message = str(exc)
    return int(message.rsplit(' ', 1)[-1]) if message.startswith('Vinyl HTTP ') and message[-3:].isdigit() else 0


def start(params):
    """The Radio Studio on the start of a playlist, a collection (its shadow playlist) or a "Nové vysílání"."""
    from wcs.vinyl import radio_studio
    if not client.account():
        raise client.LoginRequired()
    if params.get('kind') == 'create':
        act(radio_studio.show('create'))
        return
    source = _source(params.get('kind', 'playlist'), params)
    if source:
        act(radio_studio.show(source=source))


def studio(params):
    """The Radio Studio on one of its pages (the Studio row of Home, Vinyl → Rádio)."""
    from wcs.vinyl import radio_studio
    act(radio_studio.show(params.get('page') or 'live'))


def act(decision):
    """Do what the Studio chose, once its card is closed."""
    if not decision:
        return
    if decision[0] == 'tune':
        tune_id(decision[1])
    elif decision[0] == 'control':
        control({'op': decision[1], 'id': decision[2]})
    elif decision[0] == 'session':
        play_session(decision[1])
    elif decision[0] == 'launch':
        launch(*decision[1:])


def launch(payload, character, page):
    _busy(True)
    try:
        result = client.request('radio/launch', 'POST', dict(payload, characterId=character, **page), timeout=(5, 60))
    except Exception as exc:
        _busy(False)
        _log('start failed: {}'.format(exc), xbmc.LOGWARNING)
        message = text(33142) if _status(exc) == 409 else text(33131).format(exc)
        xbmcgui.Dialog().notification('Vinyl', message, xbmcgui.NOTIFICATION_ERROR)
        return
    _busy(False)
    _log('launched broadcast {} ({}, {})'.format(result['broadcast'].get('id'), character, page))
    xbmcgui.Dialog().notification('Vinyl', text(33123))
    tune(result['broadcast'])
    _rows_changed()


def _rows_changed():
    from wcs.vinyl import radio_widgets
    radio_widgets.request()


def tune_id(identity):
    """A broadcast by its id: tune in, or the creator's choice of Naladit / Další skladba / Vypnout."""
    broadcast = next((b for b in client.request('radio/broadcast', authenticated=False)['broadcasts']
                      if str(b.get('id')) == str(identity)), None)
    if not broadcast:
        xbmcgui.Dialog().notification('Vinyl', text(33124))
        _rows_changed()
        return
    if mine(broadcast):
        choice = xbmcgui.Dialog().select(broadcast.get('title') or text(33100), [text(33146), text(33125), text(33126)])
        if choice < 0:
            return
        if choice:
            control({'op': 'skip' if choice == 1 else 'stop', 'id': broadcast['id']})
            return
    tune(broadcast)


# The shadow playlist and the Studio page of a collection, named as the web names them (CollectionRadio).
SHADOW = {'album': '[auto] Album: {}', 'artist': '[auto] Artist: {}', 'genre': '[auto] Genre: {}', 'playlist': '[auto] {}'}
KICKERS = {'playlist': 32689, 'album': 33164, 'artist': 33165, 'genre': 33166}


def _source(kind, params):
    """The Studio's start of what a broadcast airs: an own playlist itself, anything else a shadow playlist of a
    random sample, whose saved choices are the collection's page as on the web."""
    from wcs.vinyl.context import owns
    identity, name = params.get('id', ''), params.get('name', '')
    if kind not in SHADOW:
        return None
    if kind == 'playlist' and owns(identity):
        songs = client.collection('playlist', identity)
        return {'kicker': text(KICKERS[kind]), 'title': name, 'count': len(songs), 'payload': {'playlistId': int(identity)},
                'page': {'pageType': 'playlist', 'pageId': str(int(identity))},
                'art': client.cover(songs[0], 'song') if songs else '', 'back': ''}
    songs = client.collection(kind, identity, name, params.get('artist', ''))
    if not songs:
        xbmcgui.Dialog().notification('Vinyl', text(32529))
        return None
    sample = random.sample(songs, SAMPLE) if len(songs) > SAMPLE else songs
    result = client.request('playlists/shadow', 'POST', {'name': SHADOW[kind].format(name or text(33100)),
                                                          'songIds': [int(s['id']) for s in sample]})
    shadow = int(result['playlistId'])
    _log('{} "{}" airs from shadow playlist {} ({} songs)'.format(kind, name, shadow, len(sample)))
    page = {'pageType': 'playlist', 'pageId': str(shadow)} if kind == 'playlist' else {'pageType': kind, 'pageId': name}
    return {'kicker': text(KICKERS[kind]), 'title': name, 'count': len(sample), 'payload': {'playlistId': shadow},
            'page': page, 'art': client.cover(sample[0], 'song'), 'back': ''}


def play_session(identity):
    """A radio card: tune in when it is on air, else its recording, else air what was prepared ahead."""
    identity = int(identity)
    for broadcast in client.request('radio/broadcast', authenticated=False)['broadcasts']:
        if int(broadcast.get('sessionId') or 0) == identity:
            tune(broadcast)
            return
    session = client.request('radio/sessions/{}/timeline'.format(identity))['session']
    if session.get('recording_file'):
        path, li = recording_item(session)
        xbmc.Player().play(path, li)
        return
    if session.get('mode') == 'pregenerated':
        try:
            tune(client.request('radio/broadcast/prepared', 'POST', {'sessionId': identity}, timeout=(5, 30))['broadcast'])
        except Exception as exc:
            _log('prepared {} failed: {}'.format(identity, exc), xbmc.LOGWARNING)
            xbmcgui.Dialog().notification('Vinyl', text(33142) if _status(exc) == 409 else text(33141), xbmcgui.NOTIFICATION_ERROR)
        return
    xbmcgui.Dialog().notification('Vinyl', text(33141))


def control(params):
    op, identity = params.get('op'), params.get('id', '')
    if op not in ('skip', 'stop') or not identity:
        return
    client.request('radio/broadcast/{}/{}'.format(identity, op), 'POST', timeout=(3, 10))
    _log('{} {}'.format(op, identity))
    if op == 'stop':
        xbmcgui.Dialog().notification('Vinyl', text(33127))
        if 'radio/broadcast/{}/'.format(identity) in (xbmc.Player().getPlayingFile() if xbmc.Player().isPlaying() else ''):
            xbmc.Player().stop()
    _rows_changed()
    xbmc.executebuiltin('Container.Refresh')


def run(handle, params):
    action = params.get('action')
    if action == 'vinyl_radio':
        root(handle)
    elif action == 'vinyl_radio_live':
        live(handle)
    elif action == 'vinyl_radio_playlists':
        playlists(handle)
    elif action == 'vinyl_radio_records':
        records(handle)
    elif action == 'vinyl_radio_create':
        start(dict(params, kind='create'))
    elif action == 'vinyl_radio_start':
        start(params)
    elif action == 'vinyl_radio_session':
        play_session(params.get('id', 0))
    elif action == 'vinyl_radio_control':
        control(params)
    elif action == 'vinyl_radio_studio':
        studio(params)
    elif action == 'vinyl_radio_tune':
        tune_id(params.get('id', ''))
