# -*- coding: utf-8 -*-
"""One-time reset of the addon settings to the shipped defaults (resources/settings.xml).

The defaults are the settings of the maintainer's Kodi (scripts/snapshot_defaults.py). The service calls
enforce_addon_defaults() at every start; it is one setting read unless this install has not been reset to
DEFAULTS_VERSION yet. Then every bool/select/number/slider setting is set to its default once. Text and folder settings
(API keys, tokens, logins, passwords, folders, status labels) are never touched, and neither is any id that looks like
a credential. The skin half lives in wcs/skin/defaults.py.

To force the defaults again in a later release: refresh them with scripts/snapshot_defaults.py, set DEFAULTS_VERSION to
that release and raise the skin flag (wcs/skin/defaults.py FLAG and Home.xml).
Nothing heavy is imported at module level: the service imports this module on every start.
"""
DEFAULTS_VERSION = '2.1.51'
MARKER = 'defaults_applied_version'            # setting that remembers the last reset
RESET_TYPES = ('bool', 'select', 'number', 'slider')
S_RESET_DONE = 32548


def is_protected(setting_id):
    """Ids that look like credentials or device identity: kept as they are, whatever their type."""
    import re
    return bool(re.search(r'api_key|login|pass(word)?$|^wspass$|^wsuser$|(^|_)user$|(^|_)token$|auth|secret|uuid',
                          setting_id, re.I))


def resettable_defaults(settings_xml):
    """{setting id: default} of the settings the reset may change, from the settings.xml at that path."""
    import xml.etree.ElementTree as ET
    return {node.get('id'): node.get('default') for node in ET.parse(settings_xml).getroot().iter('setting')
            if node.get('id') and node.get('type') in RESET_TYPES and node.get('default') is not None
            and not is_protected(node.get('id'))}


def enforce_addon_defaults(addon):
    """Reset once per install; returns the ids that changed, or None when this install is already on DEFAULTS_VERSION."""
    if addon.getSetting(MARKER) == DEFAULTS_VERSION:
        return None
    import os
    import xbmc
    import xbmcvfs
    changed = []
    for setting_id, default in resettable_defaults(
            os.path.join(xbmcvfs.translatePath(addon.getAddonInfo('path')), 'resources', 'settings.xml')).items():
        if addon.getSetting(setting_id) != default:
            addon.setSetting(setting_id, default)
            changed.append(setting_id)
    addon.setSetting(MARKER, DEFAULTS_VERSION)
    xbmc.log('[Milionář Service] Výchozí nastavení: {} položek přepsáno'.format(len(changed)), level=xbmc.LOGINFO)
    if changed:
        import xbmcgui
        xbmcgui.Dialog().notification('Milionář', addon.getLocalizedString(S_RESET_DONE), xbmcgui.NOTIFICATION_INFO, 5000)
    return changed
