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

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

group = "ombg"
varname = "totalSnowDepth" 

daHofxPath1="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/C768/DA_GHCN_HR2/DA/hofx"
daHofxPath2="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/C768/DA_GHCN_HR2_bugFix/DA/hofx"
PlotPath="/scratch1/NCEPDEV/da/Youlong.Xia/DA_plotScripts/pythonScripts/plots/C768HR2_bugfix_check/"
fname = PlotPath+group+"_"+varname+"C768_Russia_stdev_timeseries_WY2020.png"

RestartDate = "2019-10-01"
DeltaTime = 1  # day
SimulationDuration = 366  # days
RestartDate = datetime.strptime(RestartDate, '%Y-%m-%d')

DA_avg11 = np.empty([SimulationDuration])
DA_avg21 = np.empty([SimulationDuration])

DA_avg11[:] = np.nan
DA_avg21[:] = np.nan

xx = np.empty([SimulationDuration])

# North America [-155 - -60oW, 40 - 70oN]
# Europe [0 -45E, 40-70N]
# Russia [45-150, 40-70oN]

latmin = 40.0
latmax = 70.0
lonmin = 45
lonmax = 150

for SimDay in range(SimulationDuration):
    PassedTimeStepNo = (SimDay)
    ThisRestartDate = RestartDate + timedelta(days=PassedTimeStepNo * DeltaTime)
    print(ThisRestartDate)
    str_yr = ThisRestartDate.strftime('%Y')
    str_mh = ThisRestartDate.strftime('%m')
    str_dy = ThisRestartDate.strftime('%d')
    date = str_yr+str_mh+str_dy

    xx[SimDay] = SimDay
    HofxFile11 = daHofxPath1+"/letkf_hofx_ghcn_"+date+"00.nc"     
    HofxFile21 = daHofxPath2+"/letkf_hofx_ghcn_"+date+"00.nc"
    
    ombg11 = ReadNETCDF(HofxFile11 ,"ombg","totalSnowDepth")
    ombg21 = ReadNETCDF(HofxFile21 ,"ombg","totalSnowDepth")
    latout =  ReadNETCDF(HofxFile11 ,"MetaData", "latitude")
    lonout = ReadNETCDF(HofxFile11 ,"MetaData", "longitude")

    qc11 = ReadNETCDF(HofxFile11,"EffectiveQC0","totalSnowDepth")
    qc12 = ReadNETCDF(HofxFile11,"EffectiveQC1","totalSnowDepth")
    qc21 = ReadNETCDF(HofxFile21,"EffectiveQC0","totalSnowDepth")
    qc22 = ReadNETCDF(HofxFile21,"EffectiveQC1","totalSnowDepth")

    da11 = np.empty([len(latout)])
    da21 = np.empty([len(latout)])

    da11[:] = np.nan
    da21[:] = np.nan

    # fill values for a region
    for k in range(len(latout)):
       if (latout[k]>=latmin) & (latout[k]<=latmax) & (lonout[k]>=lonmin) & (lonout[k]<=lonmax):
            if(qc11[k] == 0 and qc12[k] == 0):
                da11[k] = ombg11[k]
            if(qc21[k] == 0 and qc22[k] == 0):
                da21[k] = ombg21[k]

    avg11= np.nanstd(da11)
    avg21= np.nanstd(da21)

    DA_avg11[SimDay] = avg11
    DA_avg21[SimDay] = avg21
    #exit()
# plot global averaged snow depth time series
plt.figure(figsize=(12,8))
ax1 = plt.subplot(1, 1, 1)
ax1.set_ylim(0, 200.0)
ax1.plot(xx,DA_avg11,'r-',label="DAghcn HR2 fv3-jedi bug: stdev(O-F)")
ax1.plot(xx,DA_avg21,'g-',label="DAghcn HR2 fv3-jedi bug fixed: stdev(O-F)")
ax1.set_ylabel("Snow Depth (mm)", fontsize=20)
ax1.set_xlabel("Simulation Days Since 1 October 2019", fontsize=20)
ax1.legend()
plt.tight_layout()
plt.savefig(fname)
plt.close()
