# This script is used to download seasonal data from the CDS and is aimed at providing an example of how the seasonal hindcast and observations can be downloaded using R. 

#tot açò s ha de definir fora del script

library(ecmwfr)
library(lubridate)
library(multiApply)

#user_cds <- "26595"

#cds.key <- "88fd13cb-fd28-4441-966d-2c94735e3b7c"
#wf_set_key(user = user_cds, key = cds.key, service = "cds")


# Select variable
var_name = 'tas'

# Specify the reference period for forecast calibration ("years"), and the inisialization month ("ini" - in this case November (11)):
ini="05"
years <- c(1995:2010)

sdate_forecast <- paste0(years,ini) #Array with the initialisation dates. In this case 199911,200011,...,201411,201511

# Specify forecast lead time
time_forecast <- seq(1,3) # As the initialisation month is November (ini=11),
                              # the predicted months will be November, December and January (NDJ)

lons.min <- 0
lons.max <- 49
lats.min <- -40
lats.max <- -10


netcdf_obs_dates <-array(numeric(),c(sdate=length(sdate_forecast),time=length(time_forecast)))
netcdf_hcst_dates <-array(numeric(),c(sdate=length(sdate_forecast),time=1))
netcdf_hcst_dates[,1]<-sdate_forecast



####Definition of the fubctions
get_month_year <-function(date){

        ####Fer un diccionari de variables 
        month<-substr(date,5,6)
        year <-substr(date,1,4)

        return(list(month,year))
}


### Obtain the observations and hcst netcdfs
.download_seasonal_R <- function(type,dates_to_download)
{

for (fcst_time in (1:length(time_forecast)))
{
        for (year in (1:length(sdate_forecast)))
        {
                download_seasonal_R(month=dates_to_download$month[year,fcst_time],year=dates_to_download$year[year,fcst_time],
                                    variable=var_name,type=type)
        }
}

}



download_seasonal_R <-function(month,year,variable,type){

 switch (tolower(variable),
      "tas"     = {var_name_cds <- '2m_temperature'},
      "tasmax"     = {var_name_cds <- '2m_temperature'},
      "tasmin"     = {var_name_cds <- '2m_temperature'},
      "prlr"     = {var_name_cds <- '2m_temperature'},
      "sfcwind"= {var_name_cds <- '2m_temperature'},
      "solarradiation"= {var_name_cds <- '2m_temperature'})


switch (tolower(type),
      "obs"     = {dataset_short_name <- "reanalysis-era5-single-levels-monthly-means"; product_type <- "monthly_averaged_reanalysis";
                   outdir = paste0("./esarchive/recon/ecmwf/era5/monthly_mean/downloaded/",variable,"-r1440x721cds/");
                   outfile =paste0(variable,"_",year,month,".nc")},

      "hcst"     = {dataset_short_name <- "seasonal-monthly-single-levels"; product_type <- "monthly_mean";
                    leadtime_month<-seq(1,6); system <-"5"; originating_centre <- "ecmwf";
                    outdir = paste0("./esarchive/exp/ecmwf/system5c3s/monthly_mean/downloaded/",variable);
                    outfile =paste0(variable,"_",year,month,"01.nc")}) 

dir.create(
  outdir,
  showWarnings = TRUE,
  recursive = TRUE,
  mode = "0777"
)


if (tolower(type) == "obs")
{
        request <- list(
        dataset_short_name = dataset_short_name,
        product_type   = product_type,
        format = "netcdf",
        variable = var_name_cds,
        year=year,
        month=month,
        time = c("00:00"),
        # area is specified as N, W, S, E
        area = c(lats.max, lons.min, lats.min, lons.max),
        target = outfile)

} else{
        request <- list(
        dataset_short_name = dataset_short_name,
        system = system,
        originating_centre <- originating_centre,
        leadtime_month <- leadtime_month,
        product_type   = product_type,
        format = "netcdf",
        variable = var_name_cds,
        year=year,
        month=month,
        time = c("00:00"),
        # area is specified as N, W, S, E
        area = c(lats.max, lons.min, lats.min, lons.max),
        target = outfile)

}



file <- wf_request(user = user_cds,
                     request = request,
                     transfer = TRUE,
                     path ="./", #outdir,
                     verbose = TRUE)



}





for(fcst_time in (1:length(time_forecast)))
{
        dates_lt<-as.Date(paste0(sdate_forecast,"01"),format="%Y%m%d") %m+% months(time_forecast[fcst_time]) %m-% months(1)
        dates_lt<-format(dates_lt,"%Y%m%d") 
        dates_lt <-substr(dates_lt,1,6)
        netcdf_obs_dates[,fcst_time]<-dates_lt             

}


#load obs 

dates_to_download_obs<-multiApply::Apply(data = list(date=netcdf_obs_dates),target_dims =c("sdate","time"), fun = get_month_year)     
names(dates_to_download_obs)<-c("month","year")
 
dates_to_download_hcst<-multiApply::Apply(data = list(date=netcdf_hcst_dates),target_dims =c("sdate","time"), fun = get_month_year)
names(dates_to_download_hcst)<-c("month","year")




#.download_seasonal_R(type="obs",dates_to_download=dates_to_download_obs)
.download_seasonal_R(type="hcst",dates_to_download=dates_to_download_hcst)


