from copy import deepcopy
from netCDF4 import Dataset
from mpi4py import MPI
import numpy as np

CHIMERE_GLOBAL_ATTRS = {
    "Title": "CHIMERE SUITE",
    "Sub-title": "Emissions file - Surfacic + Point sources + Fires",
    "Generating_process": "Generated by Hermes_delta",
    "Conventions": "",
    "Domain": "EU027n",
    "history": "",
}
CONSTANTS = {
    "SpStrLen": 23,
    "DateStrlen": 19
}

def to_netcdf_chimere(self, path, keep_open=True):
    # Open NetCDF
    if self.info:
        print("Rank {0:03d}: Creating {1}".format(self.rank, path))
    if self.size > 1:
        netcdf = Dataset(
            path,
            format="NETCDF4",
            mode="w",
            parallel=True,
            comm=self.comm,
            info=MPI.Info(),
        )
    else:
        netcdf = Dataset(path, format="NETCDF4", mode="w", parallel=False)
    if self.info:
        print("Rank {0:03d}: NetCDF ready to write".format(self.rank))

    set_global_attributes(self)
    create_and_convert_time(self, netcdf)

    lat=netcdf.createVariable("lat", "f4", ("south_north", "west_east"))
    lat.units="degrees_east"
    lat.long_name="Latitude"
    lon=netcdf.createVariable("lon", "f4", ("south_north", "west_east"))
    lon.units="degrees_north"
    lon.long_name="Longitude"




def _create_dimensions_chimere(self, netcdf):
    netcdf.createDimension("Time", None)


# Overwrite global attributes, but carry over any that match the key
def set_global_attributes(self):
    self.global_attrs = {**CHIMERE_GLOBAL_ATTRS, **self.global_attrs}

def create_and_convert_time(self, netcdf):
    formatted_times = [t.strftime("%Y-%m-%d_%H:%M:%S") for t in self.time]
    times_array = np.array([list(s.ljust(CONSTANTS["DateStrlen"])) for s in formatted_times], dtype='S1')

    netcdf.createDimension("Time", len(formatted_times))
    netcdf.createDimension("DateStrLen", CONSTANTS["DateStrlen"])

    time_var = netcdf.createVariable("Times", "S1", ("Time", "DateStrLen"))
    time_var[:, :] = times_array

