import json
import yaml
from jinja2 import Template, Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader("templates"))

def load_json_data_from_file(file_path):
    with open(file_path) as json_file:
        data = json.load(json_file)
    return data


def load_yaml_data_from_file(file_path):
    with open(file_path) as yaml_file:
        data = yaml.safe_load(yaml_file)
    return data


def render_network_config(template_name, data):
    template = env.get_template(template_name)
    return template.render(data)


def save_built_config(file_name, data):
    with open(file_name, "w") as f:
        f.write(data)
    return file_name


if __name__ == "__main__":

    #process R2
    r2_data = load_json_data_from_file(file_path='data/R2.json')
    esw2_data = load_json_data_from_file(file_path='data/ESW2.json')
    #fichier_inconnu_data = load_json_data_from_file(file_path='data/file-unknown.json')
    #print(r2_data)
    r2_config = render_network_config(template_name='R2.j2', data=r2_data)
    save_built_config('config/R2.conf', r2_config)

    #process ESW2
    esw2_data = load_json_data_from_file(file_path='data/ESW2.json')
    esw2_config = render_network_config(template_name='ESW2.j2', data=esw2_data)
    save_built_config('config/ESW2.conf', esw2_config)

    r2_data_yaml = load_yaml_data_from_file(file_path='data/R2.yaml')
    r2_config_yaml = render_network_config(template_name='R2.j2', data=r2_data_yaml)
    save_built_config('config/R2_from_yaml.conf', r2_config_yaml)
    
    esw2_data_yaml = load_yaml_data_from_file(file_path='data/ESW2.yaml')
    esw2_config_yaml = render_network_config(template_name='ESW2.j2', data=esw2_data_yaml)
    save_built_config('config/ESW2_from_yaml.conf', esw2_config_yaml)
    pass