
try:
    from API_v_1_0 import *
except:  # ImportError is not defined in sandbox
    pass

API_VERSION = 'API_v1.0'
MOD_NAME = 'UserPrefs'


class UserPrefsMethods:
    LOAD_SETTINGS = 'UserPrefsMethods.loadSettings'


class UserPrefs:
    _DB_PATH = '../../../../../profile/userprefs_%s.json'
    _settings = None

    def __init__(self, modName):
        self._modName = modName
        self._prefsPath = self._DB_PATH % modName
        self._loadSettings()

        events.onFlashReady(self.onFlashReady)
        flash.addExternalCallback('inputMapping.onAction', self._onAction)

    def _onAction(self, unknown, actionName, params):
        if actionName == 'setUserPref':
            self._settings\
                .setdefault(params['name'], {})[params['subName']] = params['value']
        utils.logInfo(actionName, params)
        self._saveSettings()
        self._updateSettings()
        

    def _loadSettings(self):
        print 'Trying to load settings from %s' % self._prefsPath

        self._settings = {}
        try:
            f = open(self._prefsPath, 'r').read()
            self._settings = utils.jsonDecode(f)
            print 'Prefs loaded %s' % self._settings
        except:
            print 'Error while loading prefs from %s' % self._prefsPath

    def _saveSettings(self):
        f = open(self._prefsPath, 'w')
        f.write(utils.jsonEncode(self._settings, indent=2))
        f.close()

    def _updateSettings(self):
        flash.call(UserPrefsMethods.LOAD_SETTINGS, [self._settings])

    def onFlashReady(self, flashName):
        if flashName == self._modName:
            self._updateSettings()
