# -*- coding: utf-8 -*-
"""Vinyl radio rows of Home (docs/plan/vinyl-radio/020): what is on air, the Studio's starts, the recordings.

The on-air and recording rows read a cache only the service writes (`refresh(row)`, scheduled by
wcs/skin/refresher.SCHEDULE); building a row never touches the network. The Studio row is a fixed set of action
cards that open the Radio Studio dialog (wcs/vinyl/radio_studio.py) on one of its pages.
"""
import json
import os
import tempfile
import time
from urllib.parse import urlencode

import xbmc
import xbmcgui
import xbmcplugin

from wcs.vinyl import client

BASE = 'plugin://plugin.video.milionar/'
LIVE, STUDIO, RECORDS = 'vinyl_radio_live', 'vinyl_radio_studio', 'vinyl_radio_records'
ROWS = (LIVE, STUDIO, RECORDS)
CACHED = {LIVE: 'radio_live', RECORDS: 'radio_records'}         # row -> cache source (client.cache_path)
# the Studio row: (dialog page, title, what the hero says, icon)
STUDIO_CARDS = (('playlists', 33145, 33150, 'DefaultMusicPlaylists.png'),
                ('create', 33103, 33151, 'DefaultAddSource.png'),
                ('live', 33101, 33152, 'DefaultAddonMusic.png'),
                ('records', 33104, 33153, 'DefaultMusicRecentlyPlayed.png'))
BROADCAST_FIELDS = ('id', 'sessionId', 'title', 'creatorUserId', 'creatorName', 'hosts', 'listeners', 'startedAt')
SONG_FIELDS = ('id', 'title', 'artist', 'cover_version')
RECORD_FIELDS = ('id', 'title', 'playlist_name', 'playlist_id', 'playlist_cover_mode', 'playlist_cover_song_ids',
                 'cover_version', 'moderator_name', 'moderator_name_2', 'created_at', 'recording_duration')


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


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


# ---- the service side
def _plain_broadcast(broadcast):
    entry = {key: broadcast[key] for key in BROADCAST_FIELDS if key in broadcast}
    now = broadcast.get('nowPlaying') or {}
    entry['nowPlaying'] = {key: now[key] for key in SONG_FIELDS if key in now} if now.get('id') else {}
    return entry


def _fetch(row):
    if row == LIVE:
        return [_plain_broadcast(b) for b in client.request('radio/broadcast', authenticated=False, timeout=(3, 10))['broadcasts']]
    sessions = client.request('radio/sessions/all', timeout=(5, 20))['sessions']
    return [{key: s[key] for key in RECORD_FIELDS if key in s} for s in sessions if s.get('recording_file')]


def _shown(row, items):
    """What a card shows, the part a changed row is published for (not the listener count of a broadcast)."""
    if row == LIVE:
        return [(e.get('id'), e.get('title'), (e.get('nowPlaying') or {}).get('id'), e.get('creatorUserId')) for e in items]
    return [(e.get('id'), e.get('title'), e.get('cover_version'), e.get('recording_duration')) for e in items]


def snapshot(row):
    try:
        with open(client.cache_path(CACHED[row]), encoding='utf-8') as handle:
            data = json.load(handle)
        return data if isinstance(data, dict) and isinstance(data.get('items'), list) else None
    except (OSError, ValueError):
        return None


def refresh(row):
    """Service job: fetch one row's data and replace its cache atomically; False asks the scheduler to retry."""
    from wcs.skin.refresh import changed
    session = client.scope()
    try:
        items = _fetch(row)
    except Exception as exc:
        _log('{} refresh failed: {}'.format(row, type(exc).__name__), xbmc.LOGWARNING)
        return False
    if client.scope() != session:
        return False
    previous = snapshot(row)
    path = client.cache_path(CACHED[row])
    try:
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=os.path.dirname(path), delete=False) as handle:
            json.dump({'items': items, 'built': time.time()}, handle)
        os.replace(handle.name, path)
    except OSError:
        return False
    if previous is None or _shown(row, previous['items']) != _shown(row, items):
        changed([row])
    return True


def request(rows=(LIVE,)):
    """Ask the service for fresh rows now (a broadcast started or ended here)."""
    from wcs.skin.refresh import request as ask
    ask(list(rows), force=True)


# ---- the rows
def _url(**params):
    return BASE + '?' + urlencode(params)


def _card(title, label2, art, builtin, hero_texts, extras):
    """A Home card that runs `builtin`; `hero_texts`: (kicker, text, button, badge, now)."""
    from wcs.skin import context, hero
    li = xbmcgui.ListItem(title, label2=label2, offscreen=True)
    li.setArt({'thumb': art, 'poster': art, 'landscape': art, 'fanart': art, 'icon': art})
    tag = li.getVideoInfoTag()
    tag.setTitle(title)
    tag.setPlot(hero_texts[1])
    li.setProperty('milionar.type', 'action')
    li.setProperty('milionar.ctxdata', context.pack({'type': 'action', 'title': title, 'extras': context.encode(extras)}))
    kicker, plot, button, badge, now = hero_texts
    backdrop = art if art.startswith('http') else ''
    hero.tile(li, title, kicker, plot, backdrop, button, builtin, badge, now)
    return li


def _attach(li, query, params, row):
    """The card's path is a playable `skin_run` of `query` (a listing resolves it to nothing and runs the action), its
    `milionar.exec` the same action for a click on Home."""
    from wcs.skin import context
    path = _url(action='skin_run', run=urlencode(query))
    li.setPath(path)
    li.setProperty('IsPlayable', 'true')
    path, li, folder = context.attach(path, li, False, context.origin(params), row, hero=False)
    li.setProperty('milionar.exec', _run(query))
    return path, li, folder


def _run(query):
    return 'RunPlugin({})'.format(_url(**query))


def studio_query(page):
    return {'action': 'vinyl_radio_studio', 'page': page}


def studio_command(page):
    return _run(studio_query(page))


def _live_cards(items, params):
    from wcs.vinyl import radio
    result = []
    for broadcast in items:
        now = broadcast.get('nowPlaying') or {}
        art = client.cover(now, 'song') if now.get('id') else 'DefaultAddonMusic.png'
        query = {'action': 'vinyl_radio_tune', 'id': broadcast['id']}
        builtin = _run(query)
        line = radio.song_line(now) or text(33139)
        people = ' · '.join(p for p in (radio.hosts(broadcast), broadcast.get('creatorName'),
                                        text(33132).format(broadcast.get('listeners') or 0)) if p)
        extras = {'tune': [text(33146), builtin], 'studio': [text(33147), studio_command('live')]}
        li = _card(broadcast.get('title') or text(33100), line, art, builtin,
                   (text(33148), "{}\n{}".format(line, people), text(33146), text(33143), people), extras)
        result.append(_attach(li, query, params, LIVE))
    return result


def _record_cards(items, params):
    from wcs.vinyl import presentation
    result = []
    for session in items:
        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)
        when = presentation.created(session.get('created_at'))
        length = presentation.duration(session.get('recording_duration')) if session.get('recording_duration') else ''
        art = client.cover(session, 'radio')
        query = {'action': 'vinyl_radio_session', 'id': session['id']}
        builtin = _run(query)
        extras = {'play': [xbmc.getLocalizedString(208), builtin], 'studio': [text(33147), studio_command('records')]}
        li = _card(title, ' · '.join(p for p in (names, when) if p), art, builtin,
                   (text(33144), ' · '.join(p for p in (names, when, length) if p), xbmc.getLocalizedString(208),
                    length, names), extras)
        result.append(_attach(li, query, params, RECORDS))
    return result


def _studio_cards(params):
    result = []
    for page, title, plot, icon in STUDIO_CARDS:
        builtin = studio_command(page)
        li = _card(text(title), text(33147), icon, builtin,
                   (text(33147), text(plot), text(33154), '', ''), {'studio': [text(33147), studio_command('playlists')]})
        result.append(_attach(li, studio_query(page), params, STUDIO))
    return result


def _limit(value):
    from wcs.vinyl.widgets import _limit as limit
    return limit(value)


def build(params):
    row = params.get('row', '')
    if row == STUDIO:
        return _studio_cards(params)
    data = snapshot(row)
    if data is None or (row == LIVE and time.time() - data.get('built', 0) > 120):
        request([row])                                   # the service builds it; this listing never waits
        if data is None:
            return []
    items = data['items'][:_limit(params.get('limit'))]
    return _live_cards(items, params) if row == LIVE else _record_cards(items, params)


def run(handle, params):
    xbmcplugin.setContent(handle, 'albums')
    try:
        items = build(params)
    except Exception as exc:                             # a broken row must never break Home
        _log('row {} failed: {}: {}'.format(params.get('row'), type(exc).__name__, exc), xbmc.LOGERROR)
        items = []
    xbmcplugin.addDirectoryItems(handle, items, len(items))
    xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
