
# Copyright 2022 - Barcelona Supercomputing Center
# Author: Etienne Tourigny, Rodrigo Martín Posada
# MIT License
from datetime import date
import numpy as np
import yaml
from yaml.loader import SafeLoader
import argparse
import os
import sys  

if __name__ == '__main__':

### Read in YAML file 
    parser=argparse.ArgumentParser()
    parser.add_argument("--model_name",type=str)
    parser.add_argument("--template_name",type=str)
    parser.add_argument("--file_name",type=str)
    parser.add_argument("--leg_length_sec",type=str)
    parser.add_argument("--cpl_freq_amip_sec",type=str)
    parser.add_argument("--StartYear",type=str)
    parser.add_argument("--StartMonth",type=str)
    parser.add_argument("--StartDay",type=str)
    parser.add_argument("--FixYear",type=str)
    args = parser.parse_args()
    ModelName = args.model_name 
    RunLengthSec = args.leg_length_sec
    TimeStepSec = args.cpl_freq_amip_sec
    StartYear = args.StartYear
    StartMonth = args.StartMonth
    StartDay = args.StartDay
    FixYear = args.FixYear

    # Check the existence of template file and experiment file. 
    template_name = args.template_name
    output_file_name = args.file_name

    current_path = os.getcwd()
    yamel_input_file_path = os.path.join(current_path,template_name)
    yamel_output_file_path = os.path.join(current_path,output_file_name)

    if os.path.isfile(yamel_input_file_path) == False: 
         print("yaml template file does not exist. Aborted", file=sys.stderr)
         raise NameError("YAML file does not exist.")
    
    if os.path.isfile(yamel_input_file_path) == True:
        print("yaml output file exists. It will be deleted.", file=sys.stderr)
        os.remove(yamel_output_file_path)
         
    # Open the template file and load the file 
    read_in_data = {}  
    with open(yamel_input_file_path) as file:
        read_in_data = yaml.load(file, Loader=SafeLoader)
        file.close()

# Modify the ReadInData based on the values passed by the RunExample 
# Modify the fields from template files 
    read_in_data['RunLengthSec'] = RunLengthSec
    read_in_data['TimeStepSec'] = TimeStepSec
    read_in_data['StartYear'] = StartYear
    read_in_data['StartMonth'] = StartMonth
    read_in_data['StartDay'] = StartDay
    read_in_data['FixYear'] = FixYear

    # ## TODO remove this part 
    # read_in_data['FileInputVars']['AMIP_sst_monthly']['interpolate'] = AMIP_interpolate
    # read_in_data['FileInputVars']['AMIP_sic_monthly']['interpolate'] = AMIP_interpolate
    # read_in_data['FileInputVars']['CO2_em_monthly']['interpolate'] = CO2_interpolate
    # read_in_data['FileInputVars']['CO2_land_monthly']['interpolate'] = CO2_interpolate
    # read_in_data['FileInputVars']['CO2_ocean_monthly']['interpolate'] = CO2_interpolate

    # Save it again
with open(output_file_name, 'w') as stream:
    yaml.dump(read_in_data, stream, sort_keys=False)

print("yaml output file created.", file=sys.stderr)

