import xarray as xr
import glob
import numpy as np

def ModAttrs(DictOri,site,label,data):
    keys=list(DictOri.keys())
    NewDict={}
    for key in range(len(keys)):
        if site==key:
            NewDict[label]=data
        NewDict[keys[key]]=DictOri[keys[key]]
    return NewDict

def date2float(df,var):
    V1=df[var].astype("float64")
    return V1

def cleanAttr(var,T):
    A=T.attrs
    if var in A.keys():
        A.pop(var)
    return A

def  Corrector2(file,DataEntry,DataSal):
    T=xr.open_dataset(DataEntry+file)
    T.DoY_DHW4cal.attrs={'long_name': 'first day of the year when DHW exceeds 4 degree-weeks',
        'units': 'day of the year',
        'comment': 'considering January 1st the first day of the year'}
    T.DoY_DHW8cal.attrs={'long_name': 'first day of the year when DHW exceeds 8 degree-weeks',
        'units': 'day of the year',
        'comment': 'considering January 1st the first day of the year'}
    data =T.DHW_q99[0,:,:].values
    T["nCellsTotal"]=np.count_nonzero(np.isnan(data))+np.count_nonzero(~np.isnan(data))
    T["nCellsValid"]=np.count_nonzero(~np.isnan(data))
    T.nCellsTotal.attrs={"long_name": "number of data cells in selected area"} 
    T.nCellsValid.attrs={ "long_name": "number of valid data cells in selected area"}
    T.to_netcdf(path=DataSal+file)

def FusionNc(Map1="/home/mario/Documentos/Ocean/NetcdfToPng/NC2023Patron/",Map2="/home/mario/Documentos/Ocean/NetcdfToPng/MapsAModificar/",SalidaDir="/home/mario/Documentos/Ocean/NetcdfToPng/MapsModificados/",file="DHW_ssp245_BCC-CSM2-MR_DHW.nc"):
    nc1 = xr.open_dataset(Map1+file,decode_times=False,decode_timedelta=False)
    nc2b = xr.open_dataset(Map2+file,decode_times=False,decode_timedelta=False)
    #nc2b=nc2b.drop_sel({"time":1986})
    #nc2b=nc2b.drop_sel({"time":1985})
    nc1["DoY_DHW4cal"]=nc2b["DoY_DHW4"]
    nc1["DoY_DHW8cal"]=nc2b["DoY_DHW8"]
    nc1["nDays_DHW4cal"]=nc2b["nDays_DHW4"]
    nc1["nDays_DHW8cal"]=nc2b["nDays_DHW8"]
    df=nc1
    try:
    	df=df.drop("quantile")
    except:
    	print("noq")
    df.attrs.keys()
    #df.attrs=ModAttrs(df.attrs,5,"label","data")
    df.attrs["time_coverage_start"]=1987
    data=df.DHW_q99[0,:,:].values
    df.attrs=ModAttrs(df.attrs,5,"region_name","Global")
    #df["nCellsTotal"]=np.count_nonzero(np.isnan(data))+np.count_nonzero(~np.isnan(data))
    #df["nCellsValid"]=np.count_nonzero(~np.isnan(data))
    HH=SalidaDir+file
    df.DoY_DHW4.attrs={'long_name': "first day of the year when DHW exceeds 4 degree-weeks, relative to the climatological coldest DOY",
    'units': 'day of the year',
    'comment': "considering the coldest climatological DoY as the first day of the year"}
    df.DoY_DHW8.attrs={'long_name': "first day of the year when DHW exceeds 8 degree-weeks, relative to the climatological coldest DOY",
    'units': 'day of the year',
    'comment': "considering the coldest climatological DoY as the first day of the year"}
    df.nDays_DHW8.attrs={"long_name" : "number of days above 8 degrees-week",
    "units" : "days"}
    df.nDays_DHW4.attrs={"long_name" : "number of days above 4 degrees-week",
    "units" : "days"}
    df["nDays_DHW4"]=df["nDays_DHW4"].astype("float64")
    if np.nanmax(df["nDays_DHW4"].values)>1000:
        df["nDays_DHW4"]=df["nDays_DHW4"]/1e9/60/60/24
    df["nDays_DHW8"]=df["nDays_DHW8"].astype("float64")
    if np.nanmax(df["nDays_DHW8"].values)>1000:
        df["nDays_DHW8"]=df["nDays_DHW8"]/1e9/60/60/24
    df["nDays_DHW4cal"]=df["nDays_DHW4cal"].astype("float64")
    if np.nanmax(df["nDays_DHW4cal"].values)>1000:
        df["nDays_DHW4cal"]=df["nDays_DHW4cal"]/1e9/60/60/24
    df["nDays_DHW8cal"]=df["nDays_DHW8cal"].astype("float64")
    if np.nanmax(df["nDays_DHW8cal"].values)>1000:
        df["nDays_DHW8cal"]=df["nDays_DHW8cal"]/1e9/60/60/24
    df["nDays_DHW8"].attrs={'long_name': 'number of days above 8 degrees-week, relative to the climatological coldest DOY'}
    df["nDays_DHW4"].attrs={'long_name': 'number of days above 4 degrees-week, relative to the climatological coldest DOY'}
    df["nDays_DHW8cal"].attrs={'long_name': 'number of days above 8 degrees-week, considering January 1st the first day of the year'}
    df["nDays_DHW4cal"].attrs={'long_name': 'number of days above 4 degrees-week, considering January 1st the first day of the year'}
    mask_land = 1 * np.ones((df.dims['lat'], df.dims['lon'])) * np.isnan(df.DHW_q99.isel(time=0))
    df["mask_land"]=mask_land
    df["nDays_DHW8"]=df["nDays_DHW8"].where(df.mask_land != 1)
    df["nDays_DHW4"]=df["nDays_DHW4"].where(df.mask_land != 1)
    df["nDays_DHW8cal"]=df["nDays_DHW8cal"].where(df.mask_land != 1)
    df["nDays_DHW4cal"]=df["nDays_DHW4cal"].where(df.mask_land != 1)
    df=df.drop("mask_land")
    Tempp=list(df.var().keys())
    for i in Tempp:
        df[i].attrs=cleanAttr("coordinates",df[i])
    df.DoY_DHW8cal.attrs={'long_name': 'first day of the year when DHW exceeds 8 degree-weeks',
    'units': 'day of the year',
    'comment': 'considering January 1st the first day of the year'}
    df.DoY_DHW4cal.attrs={'long_name': 'first day of the year when DHW exceeds 4 degree-weeks',
    'units': 'day of the year',
    'comment': 'considering January 1st the first day of the year'}
    comp = dict(zlib=True, complevel=5)
    encoding = {var: comp for var in df.data_vars}
    df.to_netcdf(path=HH, encoding=encoding)

for i in glob.glob("/home/mario/Documentos/Ocean/NetcdfToPng/NC2023Patron/*"):
    A=i.split("/")[-1]
    #try:
    #SalidaDir="/home/mario/Documentos/Ocean/NetcdfToPng/MapsModificados/"
    #file=A
    print(A)
    #FusionNc(Map1="/home/mario/Documentos/Ocean/NetcdfToPng/NC2023Patron/",Map2="/home/mario/Documentos/Ocean/NetcdfToPng/MapsAModificar/",SalidaDir=SalidaDir,file=file)
    #print(1)
    #Corrector2(file,SalidaDir,"/home/mario/Documentos/Ocean/NetcdfToPng/MapCorregidoV2/")
    #print(2)
    #break
