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][:]
    return MyArray

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

def Computediff(VariName):
    print(VariName)
    DAFilePath1="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/C384/DA_GHCN_HR3/mem000/restarts/vector"
    smopsPath="/scratch2/NCEPDEV/land/data/evaluation/SMOPS/C384"

    RestartDate = "2021-01-01_00-00-00"
    DeltaTime = 1  # day
    SimulationDuration = 364  # 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)])
    smops = np.empty([len(basin)])
    smops_error = np.empty([len(basin)])
    DA_array = np.empty([len(basin)])

    DA1[:] = np.nan
    smops[:] = np.nan 
    smops_error[:] = np.nan
    DA_array[:] = np.nan
   
    smops_avg = np.empty([SimulationDuration])
    smops_up = np.empty([SimulationDuration])
    smops_bt = np.empty([SimulationDuration])
    DA_avg = np.empty([SimulationDuration])

    DA_avg[:] = np.nan
    smops_avg[:] = np.nan
    smops_up[:] = np.nan
    smops_bt[:] = 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
          
# Read DA and open loop data files

        DAFile1 = DAFilePath1+ "/ufs_land_restart_anal.%4d-%02d-%02d_%02d-%02d-%02d.nc" % (thisyear, thismonth, thisday, thishr, thismin, thissec)
        smopsFile = smopsPath+ "/smops_sm_%4d%02d%02d_C384.nc" % (thisyear, thismonth, thisday)
        
        DA_array1 = ReadNETCDF(DAFile1, VariName)
        smops_array = ReadNETCDF1d(smopsFile, "soilMoisture")
        err_array = ReadNETCDF1d(smopsFile, "uncertainty")
        
        DA_array=DA_array1[0, 0, :].ravel()

        for i in range(len(basin)):
            if basin[i] == 1229:
                if smops_array[i] > 0.0:
                    DA1[i] = DA_array[i]
                    smops[i] =smops_array[i]
                    smops_error[i] = err_array[i]

        DAavg = np.nanmean(DA1)
        smopsavg = np.nanmean(smops)
        erravg = np.nanmean(smops_error)
        
        DA_avg[SimDay] = DAavg
        smops_avg[SimDay] = smopsavg
        smops_up[SimDay] = smopsavg+0.5*erravg
        smops_bt[SimDay] = smopsavg-0.5*erravg

    plt.figure(figsize=(12,8))
    ax1 = plt.subplot(1, 1, 1)
    ax1.set_ylim(0.0, 0.3)
    ax1.plot(xx,DA_avg,'r-',label="GHCN DA")
    ax1.plot(xx,smops_up,'b-',label="smops+0.5sigma")
    ax1.plot(xx,smops_bt,'g-',label="smops-0.5sigma")
    ax1.plot(xx,smops_avg,'k-',label="smops") 
    ax1.set_ylabel("Volumetric Soil Moisture", fontsize=20)
    ax1.set_xlabel("Simulation days since 01 January 2021", fontsize=20)
    ax1.set_title("Nile River Basin", 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/C384/GRDC_C384.nc"
PlotPath= "./plots/"
fname = "Nile_river_basin_da_smops_2021.png"

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