# Copyright 2021 - Barcelona Supercomputing Center
# Author: Rodrigo Martín Posada
# MIT License
import f90nml
import numpy as np

NAMELIST_FILE_NAME = 'namelist.amip'


def read_namelist():
    # Read namelist
    nml = f90nml.read(NAMELIST_FILE_NAME)
    nml_dict = nml['NAMAMIP']
    RunLengthSec = nml_dict['RunLengthSec']
    TimeStepSec = nml_dict['TimeStepSec']
    StartYear = nml_dict['StartYear']
    StartMonth = nml_dict['StartMonth']
    StartDay = nml_dict['StartDay']
    FixYear = nml_dict['FixYear']
    LDebug = nml_dict['LDebug']

    if 'Vars' in nml_dict:
        vars_data = np.transpose(nml_dict['Vars'])
        vars_config = [None] * vars_data.shape[0]
        for i in range(len(vars_config)):
            curr_data = vars_data[i]
            conf = {
                'id': curr_data[0],
                'grid_name': curr_data[1],
                'oasis_name': curr_data[2],
                'file_pattern': curr_data[3],
                'netcdf_variable': curr_data[4],
                'yref_min': curr_data[5],
                'yref_max': curr_data[6],
                'timestep': curr_data[7],
                'interpolate': curr_data[8],
                'scale_factor': curr_data[9],
                'offset': curr_data[10],
                'min': curr_data[11],
                'max': curr_data[12],
            }
            vars_config[i] = conf
    else:
        # Backwards compatibility
        # Old namelist configuration for AMIP forcing
        vars_config = [
            {
                'id': 'AMIP_sst_monthly',
                'grid_name': 'AMIP',
                'oasis_name': 'AMIP_sst',
                'file_pattern': nml_dict['FileListSST'],
                'netcdf_variable': 'tosbcs',
                'yref_min': 1870,
                'yref_max': 2016,
                'timestep': 'monthly',
                'interpolate': nml_dict['LInterpolate'],
                'scale_factor': 1,
                'offset': 273.15,
                'min': 271.38,
                'max': None,
            },
            {
                'id': 'AMIP_sic_monthly',
                'grid_name': 'AMIP',
                'oasis_name': 'AMIP_sic',
                'file_pattern': nml_dict['FileListSIC'],
                'netcdf_variable': 'siconcbcs',
                'yref_min': 1870,
                'yref_max': 2016,
                'timestep': 'monthly',
                'interpolate': nml_dict['LInterpolate'],
                'scale_factor': 0.01,
                'offset': 0,
                'min': 0,
                'max': 1,
            }
        ]

    return RunLengthSec, TimeStepSec, StartYear, StartMonth, StartDay, FixYear, LDebug, vars_config
