import netCDF4
import matplotlib.pyplot as plt
import cartopy.feature as cfeature
import numpy as np
import pandas as pd
import cartopy.crs as ccrs
import os
from datetime import datetime
from datetime import timedelta
from dateutil.relativedelta import relativedelta

def ReadNETCDF(FilePath, VariName):
    f = netCDF4.Dataset(FilePath)
    MyArray = f.variables[VariName][:].ravel()
    return MyArray

def ReadNETCDF_2D(FilePath, VariName):
    f = netCDF4.Dataset(FilePath)
    MyArray = f.variables[VariName][:]
    return MyArray

def Computediff(VariName):
    print(VariName)
    DAFilePath1="/scratch1/NCEPDEV/stmp4/Youlong.Xia/landDA/cycle_land/C768/DA_GHCN_2015to2020/mem000/restarts/vector"
    DAFilePath2="/scratch2/NCEPDEV/stmp3/Youlong.Xia/landDA/cycle_land/C768/DA_imsGHCN_2015to2020/mem000/restarts/vector"
    OpenloopFilePath="/scratch1/NCEPDEV/stmp4/Youlong.Xia/landDA/cycle_land/C768/openloop_ghcnHOFX_2015to2020/mem000/restarts/vector"
    modisFilePath="/scratch2/NCEPDEV/land/data/evaluation/MODIS/albedo/C768/"

    fname = "C768_NorthAmerica_"+VariName+"_modis_timeseries_2018.png"

    RestartDate = "2017-10-01_00-00-00"
    DeltaTime = 1  # day
    SimulationDuration = 240  # days

    RestartDate = datetime.strptime(RestartDate, '%Y-%m-%d_%H-%M-%S')
#we want to create 3 dataframe: 1) Truth_stdDF: the rows are locations and columns are truth value at each time step and the last column will be the standard deviation of truth, 2) diff_averageDF: the rows are same as previous and each column
#is difference between OI and Truth at each time step, the last column will be average of diffs at each row (location), 3) diff2_rmseDF: rows same as previous but each column will be diff**2 and the last column will be RMSE that is sqrt of average diff**2

#   defined the basin mask
    basin = ReadNETCDF(BasinPath, "basins")

    DA1 = np.empty([len(basin)])
    DA2 = np.empty([len(basin)])
    Openloop = np.empty([len(basin)])
    modis =  np.empty([len(basin)])
    DA_albedo = np.empty([len(basin)])
    open_albedo = np.empty([len(basin)])

    DA1[:] = np.nan
    DA2[:] = np.nan
    Openloop[:] = np.nan
    modis[:] = np.nan 
   
    modis_avg = np.empty([SimulationDuration]) 
    model_avg = np.empty([SimulationDuration])
    DA_avg1 = np.empty([SimulationDuration])
    DA_avg2 = np.empty([SimulationDuration])

    model_avg[:] = np.nan
    DA_avg1[:] = np.nan
    DA_avg2[:] = np.nan
    modis_avg[:] = np.nan

    xx = np.empty([SimulationDuration])

    # North America [205 - 300o, 40 -70oN]
    # Europe [0 -45E, 40-70N]
    # Russia [45-150, 40-70]

    latmin = 40
    latmax = 70.0
    lonmin = 205.0
    lonmax = 300.0
    
    for SimDay in range(SimulationDuration):
        PassedTimeStepNo = (SimDay)
        ThisRestartDate = RestartDate + timedelta(days=PassedTimeStepNo * DeltaTime)
        print(ThisRestartDate)
        xx[SimDay] = SimDay

        thisyear, thismonth, thisday, thishr, thismin, thissec = ThisRestartDate.year, ThisRestartDate.month, ThisRestartDate.day, ThisRestartDate.hour, ThisRestartDate.minute, ThisRestartDate.second

        str_yr = ThisRestartDate.strftime('%Y')
        str_mh = ThisRestartDate.strftime('%m')
        str_dy = ThisRestartDate.strftime('%d')
        day_str = str_yr+str_mh+str_dy
          
# Read DA and open loop data files
        modisFile = modisFilePath+"MCD43C3.A"+day_str+".061.C768.nc"
        DAFile1 = DAFilePath1+ "/ufs_land_restart_back.%4d-%02d-%02d_%02d-%02d-%02d.nc" % (thisyear, thismonth, thisday, thishr, thismin, thissec)
        DAFile2 = DAFilePath2+ "/ufs_land_restart_back.%4d-%02d-%02d_%02d-%02d-%02d.nc" % (thisyear, thismonth, thisday, thishr, thismin, thissec)
        openloopFile = OpenloopFilePath+ "/ufs_land_restart_back.%4d-%02d-%02d_%02d-%02d-%02d.nc" % (thisyear, thismonth, thisday, thishr, thismin, thissec)

        if (SimDay == 0):
            latout = ReadNETCDF(modisFile, "lat")
            lonout = ReadNETCDF(modisFile, "lon")

        if (VariName == "snow_cover_fraction"):
            modis_array = ReadNETCDF(modisFile, "percent_snow")

        DA_array1 = ReadNETCDF(DAFile1, VariName)
        DA_array2 = ReadNETCDF(DAFile2, VariName)
        Openloop_array = ReadNETCDF(openloopFile, VariName)

        for i in range(len(basin)):
            if (latout[i]>=latmin) & (latout[i]<=latmax) & (lonout[i]>=lonmin) & (lonout[i]<=lonmax):
                if (modis_array[i] > 0.0): 
                    DA1[i] = DA_array1[i]
                    DA2[i] = DA_array2[i]
                    Openloop[i] = Openloop_array[i]
                    modis[i] = 0.01*modis_array[i]
        modelavg = np.nanmean(Openloop)
        DAavg1 = np.nanmean(DA1)
        DAavg2 = np.nanmean(DA2)
        modisavg = np.nanmean(modis)
        model_avg[SimDay] = modelavg
        DA_avg1[SimDay] = DAavg1
        DA_avg2[SimDay] = DAavg2
        modis_avg[SimDay] = modisavg
        #print(DAavg1, DAavg2, modelavg, modisavg)
    plt.figure(figsize=(12,8))
    ax1 = plt.subplot(1, 1, 1)
    ax1.set_ylim(0.0, 1.0)
    ax1.plot(xx,model_avg,'b-',label="openloop")
    ax1.plot(xx,DA_avg1,'r-',label="DA GHCN")
    ax1.plot(xx,DA_avg2,'g-',label="DA IMS+GHCN")
    ax1.plot(xx,modis_avg,'k-o',label="MODIS") 
    ax1.set_ylabel("snow cover fraction", fontsize=20)
    ax1.set_xlabel("Simulation days since 01 October 2017", fontsize=20)
    ax1.set_title(VariName+" comaprison in North America", pad=20, fontsize=20)
    ax1.legend()
    plt.tight_layout()
    plt.savefig(os.path.join(PlotPath, fname))
    plt.close()
    
BasinPath = "/scratch2/NCEPDEV/land/data/evaluation/basins/C768/GRDC_C768.nc"
PlotPath= "/scratch1/NCEPDEV/da/Youlong.Xia/DA_plotScripts/pythonScripts/plots/C768_multiYear/"

VarList=["snow_cover_fraction"]
for var in VarList:
    Computediff(var)
