# -*- coding: utf-8 -*-
"""Shipped skin defaults of skin.milionar: Home menu, skin switches, Home widgets and their context menus.

resources/defaults/skin.json is a snapshot of the maintainer's skin settings (scripts/snapshot_defaults.py). The skin
Home `<onload>` runs the `skin_defaults` action once for every install whose skin settings do not carry FLAG yet,
so everybody who updates gets these defaults once; slots.write_defaults ("Obnovit výchozí widgety") uses them too.
To force the defaults again in a later release, raise the flag name here and in Home.xml (MilionarDefaultsV9 -> V10).
"""
import json
import os

import xbmc
import xbmcaddon
import xbmcvfs

ADDON_ID = 'plugin.video.milionar'
FLAG = 'MilionarDefaultsV9'
_cache = []


def load():
    """The parsed skin.json ({} when missing or broken)."""
    if not _cache:
        path = os.path.join(xbmcvfs.translatePath(xbmcaddon.Addon(ADDON_ID).getAddonInfo('path')),
                            'resources', 'defaults', 'skin.json')
        try:
            with open(path, encoding='utf-8') as handle:
                _cache.append(json.load(handle))
        except (OSError, ValueError) as error:
            xbmc.log('[Milionář Skin] skin.json: {}'.format(error), level=xbmc.LOGWARNING)
            return {}
    return _cache[0]


def section(sec):
    """{'widgets': [...], 'hidewatched': bool, 'upcoming': bool} of a Home section, or None."""
    return load().get('sections', {}).get(sec)


def apply():
    """Write every shipped default to the skin; returns True when something was written (the skin must be reloaded)."""
    data = load()
    if not data:
        return False
    from wcs.skin import slots
    slots.apply_defaults()
    for name, value in data.get('strings', {}).items():
        slots._set(name, value)
    for name, on in data.get('flags', {}).items():
        xbmc.executebuiltin('Skin.SetBool({})'.format(name) if on else 'Skin.Reset({})'.format(name), True)
    xbmc.executebuiltin('Skin.SetBool({})'.format(FLAG), True)
    xbmc.log('[Milionář Skin] výchozí nastavení skinu zapsáno', level=xbmc.LOGINFO)
    return True
