# -*- coding: utf-8 -*-
"""Music card and hero properties. Cache-only; no account lookups or REST calls."""
import calendar
import time
from urllib.parse import urlencode

import xbmc

from wcs.skin import hero, performance
from wcs.vinyl import client

KINDS = {'song': 32503, 'playlist': 32689, 'artist': 32505, 'album': 32504,
         'genre': 32507, 'radio': 32508}


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


def tracks(count):
    """"1 skladba", "3 skladby", "5 skladeb": the Czech and Slovak plural of the track count."""
    count = int(count or 0)
    return text(32780 if count == 1 else 32781 if 2 <= count <= 4 else 32530).format(count)


def command(params):
    return 'RunPlugin(plugin://plugin.video.milionar/?{})'.format(urlencode(params))


def duration(seconds):
    seconds = int(seconds or 0)
    return '{}:{:02d}'.format(seconds // 60, seconds % 60)


def created(value):
    """'5. 10. 2026 22:27' in local time from the API's UTC 'YYYY-MM-DD HH:MM:SS'; '' when it is not one."""
    try:
        date, clock = str(value or '').replace('T', ' ').split(' ')[:2]
        stamp = calendar.timegm(tuple(int(p) for p in date.split('-') + clock[:8].split(':')) + (0, 0, 0))
    except (ValueError, TypeError):
        return ''
    local = time.localtime(stamp)
    return '{}. {}. {} {}:{:02d}'.format(local.tm_mday, local.tm_mon, local.tm_year, local.tm_hour, local.tm_min)


def favorite(entry, kind, params):
    """Label and builtin of the hero's favorite button from the cached state only; ('', '') without an account."""
    if kind not in ('song', 'playlist', 'album', 'artist') or not client.account():
        return '', ''
    state = client.favorite_value(entry.get('is_favorite'))
    label = xbmc.getLocalizedString(10134) if state is None else text(32613 if state else 32612)
    values = {k: v for k, v in params.items() if k != 'click'}
    return label, command(dict(values, action='vinyl_context', op='favorite'))


def fields(entry, kind, params):
    title = entry.get('name') or entry.get('title') or entry.get('playlist_name') or ''
    artist = entry.get('primary_artist') or entry.get('artist') or ', '.join(entry.get('artists') or [])
    seconds = int(entry.get('duration') or entry.get('total_duration') or 0)
    count = tracks(entry['song_count']) if entry.get('song_count') is not None else ''
    genres = entry.get('genre') or entry.get('_genres') or ''
    names = [name.strip() for name in str(genres).split(',') if name.strip()]
    meta = ' · '.join(p for p in (artist, count, duration(seconds) if kind == 'song' and seconds else
                                  hero.runtime(round(seconds / 60)) if seconds else '', str(entry.get('year') or '')) if p)
    facts = ' · '.join(p for p in (meta, created(entry.get('created_at'))) if p)
    favorite_label, favorite_command = favorite(entry, kind, params)
    play = dict(params, action='vinyl_item', click='play' if kind == 'song' else 'play_all')
    # Read the original custom artwork for the hero, rather than a square thumbnail derivative.
    art = client.cover(entry, kind, 600 if performance.enabled() else None)
    image = client.title_image(entry, kind, 720 if performance.enabled() else 1200)
    # A title image stands for the title: no font step, so the hero draws no text title over it.
    return {'title': title, 'size': '' if image else hero.size(title),
            'kicker': hero.track(' • '.join(names[:3] or [text(KINDS[kind])]).upper()),
            'plot': hero.plot(entry.get('description') or (entry.get('album') if kind == 'song' else '')), 'left': '', 'meta': facts,
            'note': artist or count, 'rating': '', 'fanart': art, 'blur': hero.blur(art), 'cover': performance.artwork(client.cover(entry, kind)),
            'title_image': image, 'subtitle': meta,
            'play': command(play), 'detail': command(dict(params, action='vinyl_detail')),
            'shuffle': command(dict(play, click='shuffle')) if kind not in ('song', 'radio') else '',
            'favorite': favorite_command, 'favorite_label': favorite_label}


def apply(item, entry, kind, params):
    values = fields(entry, kind, params)
    # The builtins the hero buttons use as they are (wcs/skin/hero_buttons.py); a track has no track list to open.
    hero.apply(item, values, values['play'], values['detail'],
               ids=('play', '') if kind == 'song' else ('play_all', 'open'),
               labels=(xbmc.getLocalizedString(hero.S_PLAY), text(32521)))
    hero.direct(item, 'shuffle', text(32523), values['shuffle'])
    hero.direct(item, 'favorite', values['favorite_label'], values['favorite'])
    hero.default_buttons(item)
    item.setArt({'fanart': values['fanart'], 'landscape': values['fanart']})
    item.setProperty('vinyl.subtitle', values['subtitle'])
    item.setProperty('vinyl.duration', duration(entry.get('duration')) if entry.get('duration') else '')
