from pathlib import Path
from json import dump, load, dumps, loads
from shutil import copyfile

from rougail_tests.utils import config_to_dict
from rougail import Rougail, RougailConfig


def type_variable(test_name):
    tmp_file = Path("tmp/tiramisu.py")
    tmp_file.parent.mkdir(exist_ok=True)
    tmp_file.unlink(missing_ok=True)
    #
    result = Path('tests/types/result') / test_name
    result.mkdir(parents=True, exist_ok=True)
    #
    rougailconfig = RougailConfig.copy()
    rougailconfig['types'] = [f'tests/types/types/{test_name}']
    rougailconfig['main_structural_directories'] = [f'tests/types/structures/{ test_name }']
    try:
        rougailconfig['tiramisu_cache'] = str(tmp_file)
    except:
        rougailconfig['cli.tiramisu_cache'] = str(tmp_file)
    rougail = Rougail(rougailconfig=rougailconfig)
    config = rougail.run()
    #
    tiramisu_file = result / "tiramisu.py"
    if not tiramisu_file.is_file():
        copyfile(tmp_file, tiramisu_file)
#        tmp_file.copy(tiramisu_file)
    with tmp_file.open() as fh:
        tiramisu = fh.read()
    with tiramisu_file.open() as fh:
        loaded_tiramisu = fh.read()
    assert loaded_tiramisu == tiramisu, f"error in file {tiramisu_file}"
    tmp_file.unlink()
    #
    variables_file = result / "variables.json"
    configuration = dict(config_to_dict(config.value.get()))
    if not variables_file.is_file():
        with variables_file.open('w') as fh:
            dump(configuration, fh, indent=4)
    with variables_file.open('r') as fh:
        loaded_configuration = load(fh)
    assert loaded_configuration == loads(dumps(configuration)), f"error in file {variables_file}"


def test_type_variable():
    type_variable("variable")


def test_type_variables():
    type_variable("variables")


def test_type_family():
    type_variable("family")


def test_type_family_redefine():
    type_variable("family_redefine")


def test_type_family_subfamily():
    type_variable("family_subfamily")


def test_type_variable_hidden():
    type_variable("variable_hidden")
