# -*- coding: utf-8 -*-
"""The global setting Kvalita návrhů (addon settings, category of its own): what every TMDb suggestion of the addon and
the skin is judged by (wcs/quality/rules.judge). The defaults and choices live here once; resources/settings.xml offers
the same ones (scripts/library_harness/test_quality.py checks it) and a genre page's own options start from them
(wcs/genres/options.py: an override there is for that page only, it never changes the global setting).
"""
from wcs.quality import rules

# key -> (addon setting id, string id of its label, choices, default); the origin is the setting's index in ORIGINS
SETTINGS = {
    'origin': ('quality_origin', 35636, rules.ORIGINS, rules.DEFAULT),
    'west_votes': ('quality_west_votes', 35625, (5, 10, 20, 50), 10),
    'rating': ('quality_rating', 35626, (5.5, 6.0, 6.5, 7.0), 6.0),
    'nw_svc_votes': ('quality_nw_svc_votes', 35627, (20, 50, 100, 200), 50),
    'nw_votes': ('quality_nw_votes', 35628, (100, 150, 300, 500), 150),
}
THRESHOLDS = ('west_votes', 'rating', 'nw_svc_votes', 'nw_votes')
ORIGIN_LABELS = dict(zip(rules.ORIGINS, (35621, 35622, 35623, 35624)))     # Západní, Celý svět, Anime, Asie


def defaults():
    return {key: default for key, (_id, _label, _choices, default) in SETTINGS.items()}


def parse(raw):
    """{key: value} of the stored setting strings ({setting id: text}); a missing or broken one keeps its default."""
    out = defaults()
    for key, (setting, _label, choices, default) in SETTINGS.items():
        text = (raw.get(setting) or '').strip()
        try:
            if key == 'origin':
                out[key] = choices[int(text)]
            else:
                value = type(default)(float(text)) if isinstance(default, int) else float(text)
                if value in choices:
                    out[key] = value
        except (ValueError, IndexError):
            pass
    return out


def values():
    """The global thresholds and origin, read from the addon settings (the defaults outside Kodi)."""
    try:
        import xbmcaddon
        addon = xbmcaddon.Addon('plugin.video.milionar')
        return parse({setting: addon.getSetting(setting) for setting, _l, _c, _d in SETTINGS.values()})
    except Exception:
        return defaults()
