#!/bin/python

import cdsapi
import os
import sys
from configparser import ConfigParser


c = cdsapi.Client()

config_file = ConfigParser()

config_file.read(str(sys.argv[1]))

originating_centre = config_file.get("DEFAULT", "originating_centre")
system = config_file.get("DEFAULT", "system")
outdir = config_file.get("DEFAULT", "outdir")
level = config_file.get("DEFAULT", "level")

startdates = [i.strip() for i in config_file.get("DEFAULT", "startdates").split(',')]

variables = [i.strip() for i in config_file.get("DEFAULT", "variables").split(',')]


var_to_shortname = { 
  "10m_u_component_of_wind": "uas",
  "10m_v_component_of_wind": "vas",
  "10m_wind_gust_since_previous_post_processing": "windgust",
  "2m_dewpoint_temperature": "tdps",
  "2m_temperature": "tas",
  "eastward_turbulent_surface_stress": "tauu",
  "evaporation": "evap",
  "maximum_2m_temperature_in_the_last_24_hours": "tasmax",
  "mean_sea_level_pressure": "psl",
  "minimum_2m_temperature_in_the_last_24_hours": "tasmin",
  "northward_turbulent_surface_stress": "tauv",
  "runoff": "runoff",
  "sea_ice_cover": "sic",
  "sea_surface_temperature": "tos",
  "snow_density": "sndl",
  "snow_depth": "snd",
  "snowfall": "snowfall",
  "soil_temperature_level_1": "tsls1",
  "surface_latent_heat_flux": "hfls",
  "surface_net_thermal_radiation": "hflds",
  "surface_sensible_heat_flux": "rsds",
  "surface_solar_radiation_downwards": "rsdsd",
  "surface_thermal_radiation_downwards": "rlds",
  "toa_incident_solar_radiation": "tisr",
  "top_net_solar_radiation": "tnsr",
  "total_cloud_cover": "clt",
  "total_precipitation": "prlr",
  "top_net_thermal_radiation": "tnrt",
  "geopotential": "g",
  "specific_humidity": "hurs",
  "temperature": "ta",
  "u_component_of_wind": "ua",
  "v_component_of_wind": "va",
}

var_to_ecmwfshortname = { 
  "10m_u_component_of_wind": "u10",
  "10m_v_component_of_wind": "v10",
  "10m_wind_gust_since_previous_post_processing": "fg10",
  "2m_dewpoint_temperature": "d2m",
  "2m_temperature": "t2m",
  "eastward_turbulent_surface_stress": "ewss",
  "evaporation": "e",
  "maximum_2m_temperature_in_the_last_24_hours": "mx2t24",
  "mean_sea_level_pressure": "msl",
  "minimum_2m_temperature_in_the_last_24_hours": "mn2t24",
  "northward_turbulent_surface_stress": "nsss",
  "runoff": "ro",
  "sea_ice_cover": "siconc",
  "sea_surface_temperature": "sst",
  "snow_density": "rsn",
  "snow_depth": "sd",
  "snowfall": "sf",
  "soil_temperature_level_1": "stl1",
  "surface_latent_heat_flux": "slhf",
  "surface_net_thermal_radiation": "ssr",
  "surface_sensible_heat_flux": "str",
  "surface_solar_radiation_downwards": "sshf",
  "surface_thermal_radiation_downwards": "strd",
  "toa_incident_solar_radiation": "tisr",
  "top_net_solar_radiation": "tsr",
  "total_cloud_cover": "tcc",
  "total_precipitation": "tp",
  "top_net_thermal_radiation": "ttr",
  "geopotential": "z",
  "specific_humidity": "q",
  "temperature": "t",
  "u_component_of_wind": "u",
  "v_component_of_wind": "v",
}

model=originating_centre+str(system)


model_to_maxleadtime = {
  'cmcc3': 4392,
  'dwd2': 4392,
  'ecmwf4': 5160,
  'ecmwf5': 5160,
  'meteo_france5':5160,
  'meteo_france6':5064,
  'meteo_france7':5112,
  'ukmo13': 5160, 
  'ukmo14': 5160, 
  'ukmo15': 5160, 
}

var_to_freq = {
  "10m_u_component_of_wind": 6,
  "10m_v_component_of_wind": 6,
  "10m_wind_gust_since_previous_post_processing": 24,
  "2m_dewpoint_temperature": 6,
  "2m_temperature": 6,
  "eastward_turbulent_surface_stress": 24,
  "evaporation": 24,
  "maximum_2m_temperature_in_the_last_24_hours": 24,
  "mean_sea_level_pressure": 6,
  "minimum_2m_temperature_in_the_last_24_hours": 24,
  "northward_turbulent_surface_stress": 24,
  "runoff": 24,
  "sea_ice_cover": 24,
  "sea_surface_temperature": 6,
  "snow_density": 24,
  "snow_depth": 24,
  "snowfall": 24,
  "soil_temperature_level_1": 6,
  "surface_latent_heat_flux": 24,
  "surface_net_thermal_radiation": 24,
  "surface_sensible_heat_flux": 24,
  "surface_solar_radiation_downwards": 24,
  "surface_thermal_radiation_downwards": 24,
  "toa_incident_solar_radiation": 24,
  "top_net_solar_radiation": 24,
  "total_cloud_cover": 6,
  "total_precipitation": 24,
  "top_net_thermal_radiation": 24,
}


if not level :
  dataset='seasonal-original-single-levels'
else:
  dataset='seasonal-original-pressure-levels'
for startdate in startdates :
 for variable in variables :
    year=startdate[0:4]
    month=startdate[4:6]
    day=startdate[6:8]
    if variable not in var_to_freq:
      frequency = 12
    else:
      frequency = str(var_to_freq[variable])
    freqdir=str(frequency)+"hourly"
    path = os.path.join(outdir,model,freqdir,var_to_shortname[variable]+str(level))
    if not os.path.exists(path):
      os.makedirs(path) 
    outfile=os.path.join(path,str(var_to_shortname[variable])+level+"_"+str(startdate)+'.nc')
    if not os.path.isfile(outfile):
      print("Downloading model {0}, variable {1}, start date {2} to {3}".format(model,variable,startdate,outfile))
      c.retrieve(
       dataset,
       {
          'originating_centre': originating_centre ,
          'system': str(system), 
          'variable': str(variable),
          'year': str(year),
          'pressure_level': str(level),
          'month': str(month),
          'day': str(day),
          'leadtime_hour': list(range(int(frequency),int(model_to_maxleadtime[model]),int(frequency))),
          'format': 'netcdf',
       },
       outfile)
      command = 'ncrename -O -d number,ensemble -v number,realization -v .' + str(var_to_ecmwfshortname[variable]) + ',' + str(var_to_shortname[variable]) + str(level) + " " + str(outfile)
      os.system(command)
    else:
     print("{0} already there, skipping it.".format(outfile))
