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

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

def Computediff(VariName):
    print(VariName)
    DAFilePath="//scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/DA_era5/mem000/restarts/vector"
    OpenloopFilePath="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/openloop_era5/mem000/restarts/vector"
    RestartDate = "2019-10-01_18-00-00"
    DeltaTime = 1  # day
    SimulationDuration = 244  # 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")
    DA = np.empty([len(basin)])
    Openloop = np.empty([len(basin)])
    DA[:] = np.nan
    Openloop[:] = np.nan 
    
    model_avg = np.empty([SimulationDuration])
    DA_avg = np.empty([SimulationDuration])
    model_avg[:] = np.nan
    DA_avg[:] = np.nan

    xx = np.empty([SimulationDuration])

    for SimDay in range(SimulationDuration):
        print(SimDay)
        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
        DAFile = DAFilePath+ "/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)
        DA_array = ReadNETCDF(DAFile , VariName)
        Openloop_array = ReadNETCDF(openloopFile , VariName)

        for i in range(len(basin)):
            if basin[i] == 4405:
                DA[i] = DA_array[i]
                Openloop[i] =Openloop_array[i]
        modelavg = np.nanmean(Openloop)
        DAavg = np.nanmean(DA)
        model_avg[SimDay] = modelavg
        DA_avg[SimDay] = DAavg

    plt.figure(figsize=(12,8))
    ax1 = plt.subplot(1, 1, 1)
    ax1.set_ylim(0.0, 200.0)
    ax1.plot(xx,model_avg,'r-',label="openloop")
    ax1.plot(xx,DA_avg,'b-',label="DA")
    ax1.set_ylabel("Snow Depth (mm)", fontsize=20)
    ax1.set_xlabel("simulation days since 1OCT2019", fontsize=20)
    ax1.legend()
    plt.tight_layout()
    plt.savefig('test.png')
    plt.close()

BasinPath = "/scratch2/NCEPDEV/land/data/evaluation/basins/C96/GRDC_C96.nc"
PlotPath= "/scratch2/NCEPDEV/land/Youlong.Xia/landDA/plots/C96/Average_DA-OpenLoopDiffsnap/"
RMSEplot= "/scratch2/NCEPDEV/land/Youlong.Xia/landDA/plots/C96/RMSE_DA-OpenLoopDiffsnap/"


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