from configparser import ConfigParser

import gi
from gi.repository.Gimp import config_build_data_path

gi.require_version('Gimp', '3.0')
from gi.repository import Gimp
from gimphelpers import *

import os,configparser

defaultConfig = {
    'common': {
        'enable': 'brushes dynamics fonts gradients palettes patterns',
        'resources_active': '${gimp_user}/${type_l}',
        'resources_stored': '${gimp_user}/${type_l}_storage',
        'menu_path': '<${type_c}>/${type_c} Menu',
        'menu_label': 'Manage ${type_l} sets...',
        'menu_blurb': 'Put online/offline sets of ${type_l}',
        'dialog_title': '${type_c} sets manager',
        'user_home': os.path.expanduser('~/')[:-1],
        'gimp_user': Gimp.directory(),
        'gimp_data': Gimp.data_directory(),
        'use_links': 'symlink' in dir(os)
    },
    'brushes': {
    },
    'dynamics': {
    },
    'fonts': {
    },
    'gradients': {
    },
    'palettes': {
    },
    'patterns': {
    },
}

class Configuration(object):
    """Class handling all the configuration data"""

    def __init__(self, pluginFile):
        # two places to check for the .ini file:
        #   Sibling of plugin executable (.py >.ini)
        #   In the plug-in-settings/ directory of the user profile
        pluginName=os.path.splitext(os.path.basename(__file__))[0]
        userIni=os.path.join(Gimp.directory(), 'plug-in-settings',pluginName+'.ini')
        defaultIni=os.path.splitext(pluginFile)[0]+'.ini'
        self.configFilePath=userIni if os.path.isfile(userIni) else defaultIni if os.path.isfile(defaultIni) else None
        trace(f'Using config data from {self.configFilePath}')
        self.configData = configparser.ConfigParser(default_section='common',interpolation=configparser.ExtendedInterpolation())
        self.configData.read_dict(defaultConfig)
        trace('Configuration initialized OK')

    def loadConfiguration(self):
        if self.configFilePath:
            try:
                with open(self.configFilePath, 'r', encoding='utf-8') as configFile:
                    self.configData.read_file(configFile)
                trace(f'Configuration file {self.configFilePath} read successfully')
            except Exception as e:
                trace(f'Configuration file {self.configFilePath} not found or not readable: {e}')
        for resourceType in self.configData.get(self.configData.default_section,'enable').split():
            self.configData.set(resourceType,'type_c',resourceType.capitalize())
            self.configData.set(resourceType,'type_l',resourceType)

    def getValue(self, section, option):
        value = self.configData.get(section, option)
        return value

    def getDefaultValue(self, option):
        value = self.configData.get(self.configData.default_section, option)
        return value

    def getBooleanValue(self, section, option):
        value = self.configData.getboolean(section, option)
        return value


if __name__ == '__main__':
    config=Configuration('ofn3-resource-manager.ini')
    config.loadConfiguration()

    print(config.getValue('common','enable'))
    print(config.getValue('brushes','menu_label'))
    print(config.getValue('brushes','resources_active'))
    print(config.getValue('brushes','menu_path'))
    print(config.getValue('brushes','use_links'),type(config.getValue('brushes','use_links')))
    print(config.getBooleanValue('brushes','use_links'),type(config.getBooleanValue('brushes','use_links')))

