# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03_config.ipynb (unless otherwise specified).

__all__ = ['ConfigModel', 'CONFIG']

# Cell
from pathlib import Path
import os, pathlib, urllib, configparser
import rpy2.robjects
import logging

# Cell
class ConfigModel(configparser.ConfigParser):

    def __init__(self):

        ''' a custom converter we use to get a log level value from it's string representation '''
        converters={'loglevel': lambda string: getattr(logging, string)}
        super().__init__(converters=converters)

        ''' app paths'''
        self.app_dir = Path().absolute().parent

        ''' user paths '''
        self.user_dir = Path('~/.superpower_gui').expanduser()
        self.user_dir.mkdir(exist_ok=True)
        self.R_lib = self.user_dir / 'R_lib'
        self.R_lib.mkdir(exist_ok=True)
        self.user_config = self.user_dir / 'config.ini'

        ''' default config '''
        source = [str(path) for path in self.app_dir.parent.rglob('Superpower*gz')]
        source = source[0] if source else None
        defaults = {'R': {'lib_loc': self.R_lib,
                          'source': source},
                    'LOG': {'level': 'ERROR',
                            'mode': 'w',
                            'captureWarnings': True,
                            'filename': 'superpower.log'},
                    'ERRORS': {'catch_all': True}}
        self.read_dict(defaults)

        ''' read and validate user config, which overrides default '''
        if self.user_config.is_file:
            try:
                self.read(self.user_config)
                self['R']['lib_loc'] = os.path.expanduser(self['R']['lib_loc'])
                self['R']['source'] = os.path.expanduser(self['R']['source'])
                assert Path(self['R']['lib_loc']).is_dir , 'lib_loc %s is not a valid location' % self['R']['lib_loc']
                assert Path(self['R']['source']).is_file, '%s is not a valid source file' % self['R']['source']
            except Exception as e:
                pass
        self.write_user_config()

    def changeLogLevel(self):
        loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
        for logger in loggers:
            logger.setLevel(logging.INFO)

    def write_user_config(self):
        with open(self.user_config, 'w') as file:
            file.write('# This config file was created to match default app settings. You may want to change them.\n')
            self.write(file)

    def _repr_pretty_(self, p, cycle):
            for section in self.sections():
                for key, value in self[section].items():
                    p.text(key + ': ')
                    p.pretty(value)
                    p.breakable()

# Cell
CONFIG = ConfigModel()