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_values', 'write_state', 'read_state']


def check_for_config(make=True):
    try:
        config_paths()
    except FileNotFoundError as e:
        if make:
            conf_path = pathlib.Path('~/.auswerten').expanduser()
            conf_path.mkdir(parents=True)
            cwd = pathlib.Path(__file__).parent
            copyfile(cwd / 'models' / 'usermodels.py', conf_path / 'usermodels.py')
            with resource_path('resources', 'Default.agr') as fp:
               copyfile(fp, conf_path / 'Default.agr')

        else:
            raise e


def config_paths() -> pathlib.Path:
    # TODO adjust for different OS
    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'}})
            # raise FileNotFoundError('Configuration file not found')
            #
    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_values = {
    ('GUI', 'theme'): ['normal', 'pokemon'],
    ('GUI', 'color'): ['light', 'dark'],
}


def write_state(opts: dict):
    config_file = config_paths() / 'guistate.ini'
    old_opts = read_state()
    old_opts.update(opts)
    with config_file.open('wb') as f:
        pickle.dump(old_opts, f)


def read_state() -> dict:
    config_file = config_paths() / 'guistate.ini'
    if not config_file.exists():
        return {}

    with config_file.open('rb') as f:
        return pickle.load(f)
