# -*- coding: utf-8 -*-
"""What the user set for the genre browser: the addon settings (cache lifetimes, TMDb requests per page) and the
options of the genre widgets (skin strings of the widget manager). Defaults live in resources/settings.xml and
wcs/genres/options.py only; nothing here writes a setting."""
import xbmc
import xbmcaddon

from wcs.genres import contract, options
from wcs.quality import settings as quality_settings

ADDON_ID = 'plugin.video.milionar'
HOUR, DAY = 3600, 86400


def _number(addon, name):
    try:
        return int(float(addon.getSetting(name)))
    except (TypeError, ValueError):
        return None


def ttl():
    """Cache lifetimes in seconds; a setting that cannot be read keeps the source's default."""
    addon = xbmcaddon.Addon(ADDON_ID)
    out = {}
    for key, name, unit in (('genres', 'genre_ttl_genres_days', DAY), ('list', 'genre_ttl_list_hours', HOUR),
                            ('countries', 'genre_ttl_countries_days', DAY)):
        value = _number(addon, name)
        if value and value > 0:
            out[key] = value * unit
    return out


def requests_per_page():
    value = _number(xbmcaddon.Addon(ADDON_ID), 'genre_requests_per_page')
    return value if value and value > 0 else 8


def source():
    from wcs.genres import tmdb
    return tmdb.Source(ttl=ttl())


def slot_rows(sec=contract.SEC):
    """[(slot, row type)] of the used slots of a section, in their order."""
    from wcs.skin.hero_contract import slot_count
    found = []
    for n in range(1, slot_count(sec) + 1):
        row = xbmc.getInfoLabel('Skin.String(mil.{}.{}.type)'.format(sec, n))
        if row and row != 'off':
            found.append((n, row))
    return found


def widget_options(row, sec):
    """The options of the first slot of `sec` that shows `row` (its defaults when no slot does), on top of the global
    Kvalita návrhů (wcs/quality/settings.py)."""
    base = quality_settings.values()
    for n, found in slot_rows(sec):
        if found == row:
            return options.values(row, xbmc.getInfoLabel('Skin.String(mil.{}.{}.opts)'.format(sec, n)), base)
    return options.defaults(row, base)

