#!/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)



if not level :
  dataset='seasonal-monthly-single-levels'
else:
  dataset='seasonal-monthly-pressure-levels'
for startdate in startdates :
 for variable in variables :
    year=startdate[0:4]
    month=startdate[4:6]
    day=startdate[6:8]
    path = os.path.join(outdir,model,'monthly',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),
          'product_type': 'monthly_mean', 
          'variable': str(variable),
          'year': str(year),
          'pressure_level': str(level),
          'month': str(month),
          'leadtime_month': [
             '1', '2', '3',
             '4', '5', '6',
          ],
          '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))
