import configparser
import pathlib
import pickle
from shutil import copyfile
from importlib.resources import path as resource_path


__all__ = ['config_paths', 'check_for_config', 'read_configuration', 'write_configuration', 'ALLOWED_VALUE', 'write_state', 'read_state']


def check_for_config(make=True):
    try:
        conf_path = config_paths()
    except FileNotFoundError as e:
        if make:
            conf_path = pathlib.Path('~/.auswerten').expanduser()
            conf_path.mkdir(parents=True)

        else:
            raise e

    for filename in ('Default.agr', 'logo.png'):
        _file = conf_path / filename
        if not _file.exists():
            with resource_path('resources', filename) as fp:
                copyfile(fp, _file)

    if not (conf_path / 'usermodels.py').exists():
        cwd = pathlib.Path(__file__).parent
        copyfile(cwd / 'models' / 'usermodels.py', conf_path / 'usermodels.py')


def config_paths() -> pathlib.Path:
    searchpaths = ['~/.config/nmreval', '~/.auswerten', '/usr/share/nmreval']
    conf_path = None

    for p in searchpaths:
        path = pathlib.Path(p).expanduser()
        if path.exists():
            conf_path = path
            break

    if conf_path is None:
        raise FileNotFoundError('No valid configuration path found')

    return conf_path


def read_configuration() -> configparser.ConfigParser:
    try:
        config_file = config_paths() / 'nmreval.cfg'
        if not config_file.exists():
            write_configuration({'GUI': {'theme': 'normal', 'color': 'light'}})
    except FileNotFoundError as e:
        raise e

    parser = configparser.ConfigParser()
    parser.read(config_file)

    return parser


def write_configuration(opts: dict):
    config_file = config_paths() / 'nmreval.cfg'

    parser = configparser.ConfigParser()
    parser.read_dict(opts)

    with config_file.open('w') as f:
        parser.write(f)


ALLOWED_VALUE = {
    ('GUI', 'theme'): ['normal', 'pokemon'],
    ('GUI', 'color'): ['light', 'dark'],
}


def write_state(new_opts: dict):
    config_file = config_paths() / 'guistate.ini'
    opts = read_state()
    opts.update(new_opts)

    parser = configparser.ConfigParser()
    parser.read_dict(opts)

    with config_file.open('w') as f:
        parser.write(f)


def read_state() -> dict:
    config_file = config_paths() / 'guistate.ini'
    if not config_file.exists():
        return {'History': {'recent path': pathlib.Path.home()}}

    with config_file.open('rb') as f:
        try:
            opts = pickle.load(f)
            opts['recent path'] = opts.get('recent_path', pathlib.Path.home())

            return {'History': opts}
        except pickle.UnpicklingError:
            parser = configparser.ConfigParser()
            parser.read(config_file)

            return parser

