#!/usr/bin/env python3
# Copyright 2021 - Barcelona Supercomputing Center
# Author: Rodrigo Martín Posada
# MIT License

import f90nml
import pyoasis
from pyoasis import OASIS  # pylint: disable=no-name-in-module
import numpy as np
import logging

if __name__ == '__main__':

    COUPLING_INTERVAL = 2700
    RUN_LENGTH_SEC = 86400

    # Init OASIS
    comp = pyoasis.Component("NEMO_TOY")
    local_comm = comp.localcomm
    # Get rank in local communicator
    mype = comp.localcomm.rank
    npes = comp.localcomm.size

    # Unit for output messages
    out_nemo = 'NEMO_toy.out_'+str(100+mype)
    logging.basicConfig(filename=out_nemo, format='%(message)s', level=logging.DEBUG)
    logging.debug('-----------------------------------------------------------')
    logging.debug('I am NEMO-toy process with rank : {}'.format(mype))
    logging.debug('in my local communicator gathering {} processes'.format(npes))
    logging.debug('----------------------------------------------------------')

    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #  PARTITION DEFINITION
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    # Definition of the local partition
    nx = 362 * 292
    partition = pyoasis.SerialPartition(nx)

    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #  DECLARATION OF THE COUPLING FIELDS
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    out_coupling_fields={}
    out_coupling_vars=["O_SSTSST","O_TepIce","O_AlbIce","OIceFrc","OIceTck","OSnwTck"]
    for v in out_coupling_vars:
        out_coupling_fields[v] = pyoasis.Var(v, partition, OASIS.OUT)
        logging.debug('var_id {}, added as OASIS_OUT var'.format(v))

    in_coupling_fields={}
    in_coupling_vars=["O_OTaux1","O_OTauy1","O_ITaux1","O_ITauy1","O_OTaux2","O_OTauy2","O_ITaux2","O_ITauy2","O_QnsMix","O_QsrMix","OTotEvap","OTotRain","OTotSnow","O_QsrIce","O_QnsIce","O_dQnsdT","OIceEvap","O_Runoff","OCalving"]
    for v in in_coupling_vars:
        in_coupling_fields[v] = pyoasis.Var(v, partition, OASIS.IN)
        logging.debug('var_id {}, added as OASIS_IN var'.format(v))

    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #         TERMINATION OF DEFINITION PHASE
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    logging.debug('End of initialisation phase')

    comp.enddef()

    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #  TIME STEP LOOP
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    logging.debug('Timestep, field min, mean and max value')

    field_data = pyoasis.asarray(np.full(nx, -1.0))

    for itap_sec in range(0, RUN_LENGTH_SEC, COUPLING_INTERVAL):
        
        logging.debug('ITAP_SEC: {} receiving fields'.format(itap_sec))
        logging.debug(str(in_coupling_fields.keys()))
        for v, field in in_coupling_fields.items():
            field.get(itap_sec, field_data)      
            logging.debug('{} -> {:.3e} {:.3e} {:.3e}'.format( v, np.min(field_data), np.mean(field_data), np.max(field_data)))
        logging.debug('--------------------------------------\n')

        logging.debug('ITAP_SEC: {} sending fields'.format(itap_sec))
        logging.debug(str(out_coupling_fields.keys()))
        for v, field in out_coupling_fields.items():
            sigma=1
            mu=1
            field_data[:]=sigma * np.random.randn(nx) + mu
            field.put(itap_sec, field_data)
            logging.debug('{} put -> {:.3e} {:.3e} {:.3e}'.format( v, np.min(field_data), np.mean(field_data), np.max(field_data)))
            logging.debug('--------------------------------------\n')




    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    #         TERMINATION
    # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    logging.debug('End of the program')

    del comp
