# -*- coding: utf-8 -*-
"""What Kodi's player shows while a Vinyl radio plays (docs/plan/vinyl-radio).

A broadcast is one endless MP3 stream and a recording one long MP3, so Kodi alone would show one title for hours.
This service thread follows the playing file: for a live stream it reads the broadcast's state every few seconds and
shows the track (and what the moderator says) at the second the listener actually hears; for a recording it reads
the recording's marks once and follows the player's time. The creator stopping their own live broadcast ends it for
everyone, as on the web. Player callbacks only enqueue; every wait ends with Kodi's abort within a second.
"""
import queue
import re
import time

import xbmc
import xbmcgui

from wcs.vinyl import client

LIVE = re.compile(r'/radio/broadcast/([^/?|]+)/stream')
RECORDING = re.compile(r'/radio/broadcast/recording/(\d+)')
POLL = 3.0                                 # seconds between two reads of a live broadcast's state
TIMEOUT = (2, 2.5)                         # never longer than the service may take to stop


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


class Watcher(xbmc.Player):
    def __init__(self):
        super().__init__()
        self.events = queue.Queue()

    # callbacks: enqueue only
    def onPlayBackStarted(self):
        self.events.put(('started', time.time()))

    def onAVStarted(self):
        self.events.put(('av', time.time()))

    def onPlayBackStopped(self):
        self.events.put(('stopped', time.time()))

    def onPlayBackEnded(self):
        self.events.put(('ended', time.time()))

    def onPlayBackError(self):
        self.events.put(('error', time.time()))


def readable(text):
    """A comment as people read it, without the TTS tags: the Python twin of Vinyl's readableSpeech()
    (src/utils/vinyl/radio/readableSpeech.ts) — change both together."""
    text = re.sub(r'<[a-z][a-z -]{0,30}>', '', text or '', flags=re.I)
    text = re.sub(r'\[[^\]]{1,40}\]', '', text)
    text = re.sub(r'\|([^|\n]{1,40})\|', r'(\1)', text)
    text = re.sub(r'(^|\s)(Host|Hostka|Moderátor|Moderátorka)\s*:\s*', lambda m: '\n' if m.group(1) else '', text)
    text = re.sub(r'[ \t]{2,}', ' ', text)
    text = re.sub(r' +([,.!?…])', r'\1', text)
    return re.sub(r' *\n *', '\n', text).strip()


def heard(marks, second):
    """The track a listener hears at this second of a broadcast or recording, and what the moderator last said
    over it (kept until the next track: without a voice a comment has no length of its own)."""
    track = speech = None
    for mark in marks or []:
        if float(mark.get('atSec') or 0) > second:
            break
        if mark.get('kind') == 'track' and mark.get('song'):
            track, speech = mark['song'], None
        elif mark.get('kind') == 'speech':
            speech = readable(mark.get('text'))
    return track, speech


class Playing:
    """One radio file in the player; `show` writes it into the player only when something changed."""
    title = ''

    def __init__(self, path):
        self.path = path
        self.shown = None

    def show(self, player, track, speech, artist=''):
        key = ((track or {}).get('id'), speech or '')
        if key == self.shown:
            return
        self.shown = key
        li = xbmcgui.ListItem(path=self.path, offscreen=True)
        tag = li.getMusicInfoTag()
        tag.setTitle((track or {}).get('title') or self.title)
        tag.setArtist((track or {}).get('artist') or artist)
        tag.setAlbum(self.title)
        tag.setComment(speech or '')
        tag.setMediaType('song')
        if track and track.get('id'):
            art = client.cover(track, 'song')
            li.setArt({'thumb': art, 'icon': art, 'fanart': art})
        try:
            player.updateInfoTag(li)
        except RuntimeError:                  # the file just stopped
            pass


class Live(Playing):
    def __init__(self, path, broadcast_id, opened):
        super().__init__(path)
        self.id = broadcast_id
        self.opened = opened                   # when Kodi asked for the stream: the server's clock then = its first byte
        self.origin = None
        self.mine = False
        self.next_poll = 0.0
        self.artist = ''

    def tick(self, player, now):
        if now < self.next_poll:
            return
        self.next_poll = now + POLL
        try:
            broadcast = client.request('radio/broadcast/{}'.format(self.id), timeout=TIMEOUT, authenticated=False)['broadcast']
        except Exception as exc:
            _log('state of {} unavailable: {}'.format(self.id, type(exc).__name__), xbmc.LOGDEBUG)
            return
        self.title = broadcast.get('title') or ''
        self.mine = str(broadcast.get('creatorUserId')) == str(client.account())
        names = broadcast.get('hosts') or {}
        self.artist = ' & '.join(n for n in (names.get('name'), names.get('name2')) if n) or broadcast.get('creatorName') or ''
        if self.origin is None:
            self.origin = float(broadcast.get('clockSec') or 0) - (now - self.opened)
            _log('broadcast {}: stream starts at {:.1f} s{}'.format(self.id, self.origin, ' (creator)' if self.mine else ''))
        try:
            second = self.origin + player.getTime()
        except RuntimeError:
            return
        track, speech = heard(broadcast.get('marks'), second)
        self.show(player, track, speech, self.artist)

    def left(self):
        """The listener stopped: the creator's stop ends the broadcast (as on the web), a listener only leaves."""
        if not self.mine:
            return
        try:
            client.request('radio/broadcast/{}/stop'.format(self.id), 'POST', timeout=TIMEOUT)
            _log('creator stopped playback: broadcast {} stopped'.format(self.id))
        except Exception as exc:
            _log('stopping {} failed: {}'.format(self.id, exc), xbmc.LOGWARNING)


class Recording(Playing):
    def __init__(self, path, session_id):
        super().__init__(path)
        self.marks = None
        try:
            result = client.request('radio/broadcast/recording/{}/marks'.format(session_id), timeout=TIMEOUT, authenticated=False)
            self.marks = result.get('marks') or []
            self.title = (result.get('session') or {}).get('title') or ''
            _log('recording {}: {} marks'.format(session_id, len(self.marks)))
        except Exception as exc:
            _log('marks of recording {} unavailable: {}'.format(session_id, type(exc).__name__), xbmc.LOGWARNING)

    def tick(self, player, now):
        if self.marks is None:
            return
        try:
            second = player.getTime()
        except RuntimeError:
            return
        track, speech = heard(self.marks, second)
        self.show(player, track, speech)

    def left(self):
        pass


def _follow(player, opened):
    try:
        path = player.getPlayingFile()
    except RuntimeError:
        return None
    match = LIVE.search(path)
    if match:
        return Live(path, match.group(1), opened)
    match = RECORDING.search(path)
    return Recording(path, int(match.group(1))) if match else None


def run(monitor):
    """Service thread entry: follow the player until Kodi exits."""
    player = Watcher()
    playing, opened = None, 0.0
    while not monitor.waitForAbort(1):
        try:
            while True:
                event, when = player.events.get_nowait()
                if event == 'started':
                    opened = when
                elif event == 'av':
                    following = _follow(player, opened or when)
                    if playing and (not following or following.path != playing.path):
                        playing.left()          # something else plays now: the radio was left
                    playing = following
                elif event == 'stopped' and playing:
                    playing.left()
                    playing = None
                elif event in ('ended', 'error'):
                    playing = None
        except queue.Empty:
            pass
        except Exception as exc:
            _log('event failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
        if playing:
            try:
                playing.tick(player, time.time())
            except Exception as exc:
                _log('tick failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGERROR)
