import netCDF4
import datetime
from datetime import datetime
from datetime import timedelta

def AddVar(ThisRestartDateTemp):
    thisyear,thismonth,thisday, thishr, thismin, thissec=ThisRestartDateTemp.year, ThisRestartDateTemp.month,ThisRestartDateTemp.day,ThisRestartDateTemp.hour,ThisRestartDateTemp.minute,ThisRestartDateTemp.second
    print(thisyear,thismonth,thisday, thishr, thismin, thissec)
    with netCDF4.Dataset(r"/scratch1/NCEPDEV/da/Azadeh.Gholoubi/control_env/static/ufs-land_C96_static_fields.nc") as StaticFile, netCDF4.Dataset(r"/scratch1/NCEPDEV/da/Azadeh.Gholoubi/control_env/GSWP3Run/restart/ufs_land_restart.%4d-%02d-%02d_%02d-%02d-%02d.nc"%(thisyear,thismonth,thisday,thishr,thismin,thissec)) as ObsFile, netCDF4.Dataset(r"/scratch1/NCEPDEV/da/Azadeh.Gholoubi/snow_obs/synthetic_noahmp/synthetic_gswp_obs.%4d%02d%02d23.nc"%(thisyear,thismonth,thisday), "w") as dst:

        # copy meta data (global attributes all) at once via dictionary
        dst.setncatts(ObsFile.__dict__)
        # copy dimensions
        for name, dimension in ObsFile.dimensions.items():
            # dst.createDimension(name, (len(dimension) if not dimension.isunlimited() else None))
            dst.createDimension(name, (len(dimension)))

        for name, variable in ObsFile.variables.items():
            NewName=name
            if name=="snwdph":
                NewName="SNWD"
            x = dst.createVariable(NewName, variable.datatype, variable.dimensions)
            dst[NewName][:] = ObsFile[name][:]
            # copy variable attributes all at once via dictionary
            dst[NewName].setncatts(ObsFile[name].__dict__)
        #Add data from static file
        NameDict={'latitude':'lat', 'longitude':"lon", 'elevation':'elevation'}
        for name, variable in StaticFile.variables.items():
            #print(name)
            if name in ['latitude', 'longitude', 'elevation']:
                NewName=NameDict[name]
                x = dst.createVariable(NewName, variable.datatype, variable.dimensions)
                dst[NewName][:] = StaticFile[name][:]


RestartDate="2013-09-30_23-00-00"
DeltaTime=1 #day
SimulationDuration=366 #days
RestartDate= datetime.strptime(RestartDate, '%Y-%m-%d_%H-%M-%S')


for SimDay in range(1,SimulationDuration+1):
    PassedTimeStepNo=(SimDay -1)
    ThisRestartDate=RestartDate+ timedelta(days=PassedTimeStepNo*DeltaTime)
    AddVar(ThisRestartDate)