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 

daHofxPath="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/DA_era5/DA/hofx"
mdlHofxPath="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/openloop_era5/DA/hofx"
PlotPath="/scratch2/NCEPDEV/land/Youlong.Xia/landDA/cycle_land/DA_era5/DA/plots/ombg_snap/"
fname = group+"_"+varname+"_"+date+".png"
units='mm'

RestartDate = "2019100118"
DeltaTime = 1  # day
SimulationDuration = 244  # days
RestartDate = datetime.strptime(RestartDate, '%Y%m%d%h')
date = RestartDate

model_avg = np.empty([SimulationDuration])
DA_avg = np.empty([SimulationDuration])
model_avg[:] = np.nan
DA_avg[:] = np.nan

for SimDay in range(SimulationDuration):

    for i in range(0,6):

        HofxFile1=daHofxPath+"/letkf_hofx_ghcn_"+date+"_000%d.nc"%i
        HofxFile2=mdlHofxPath+"/letkf_hofx_ghcn_"+date+"_000%d.nc"%i
        #print(HofxFile)

        if i==0:
            ombg01 = ReadNETCDF(HofxFile1 ,"ombg","totalSnowDepth")
            ombg02 = ReadNETCDF(HofxFile2 ,"ombg","totalSnowDepth")

        if i==1:
            ombg11 = ReadNETCDF(HofxFile1 ,"ombg","totalSnowDepth")
            ombg12 = ReadNETCDF(HofxFile2 ,"ombg","totalSnowDepth")

        if i==2:
            ombg21 = ReadNETCDF(HofxFile1 ,"ombg","totalSnowDepth")
            ombg22 = ReadNETCDF(HofxFile2 ,"ombg","totalSnowDepth")

        if i==3:
            ombg31 = ReadNETCDF(HofxFile1 ,"ombg","totalSnowDepth")
            ombg32 = ReadNETCDF(HofxFile2 ,"ombg","totalSnowDepth")

        if i==4:
            ombg41 = ReadNETCDF(HofxFile1 ,"ombg","totalSnowDepth")
            ombg42 = ReadNETCDF(HofxFile2 ,"ombg","totalSnowDepth")

        if i==5:
            ombg51 = ReadNETCDF(HofxFile1 ,"ombg","totalSnowDepth")
            ombg52 = ReadNETCDF(HofxFile2 ,"ombg","totalSnowDepth")

    dataout1 = np.concatenate((ombg01, ombg11, ombg21, ombg31, ombg41, ombg51), axis = None)     
    dataout2 = np.concatenate((ombg02, ombg12, ombg22, ombg32, ombg42, ombg52), axis = None)
    avg1= np.nanmean(dataout1)
    avg2= np.nanmean(dataout2)
    DA_avg[SimDay] = avg1
    model_avg[SimDay] = avg2

# plot global averaged snow depth time series
 plt.figure(figsize=(12,8))
 ax1 = plt.subplot(1, 1, 1)
 ax1.set_ylim(-100, 100.0)
 ax1.plot(xx,model_avg,'r-',label="openloop: O-F")
 ax1.plot(xx,DA_avg,'b-',label="DA: O-F")
 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()

