import xarray as xr
import numpy as np
from pathlib import Path
import threading
import os
import json
import yaml


import rpy2.robjects as ro
from rpy2.robjects.packages import importr
from rpy2.robjects import numpy2ri

numpy2ri.activate()

class script:
    
    def extract_attrs(self,
                      dataarray,
                      attrs_in = ['GRIB_cfVarName', 'GRIB_units'],
                      attrs_out = None
                     ):
        
        # This function extract the specific attributes from the given dataarray providing a dictionary attrs

        if attrs_out is None:
            attrs_out = attrs_in
            
        attrs = dict()
        for in_i, out_i in zip(attrs_in, attrs_out):
            attrs[out_i] = dataarray.attrs[in_i]
            
        return attrs
    
    def autopdffunction(self,
                        year0,
                        year1,
                        ksl_centersystem,
                        ksl_centersystemname,
                        ksl_units, 
                        ksl_varname,
                        ksl_varname_long,
                        ksl_plevel,
                        p850,
                        p500,
                        p200,
                        p50,
                        workdir,
                        ksl_inputpath,
                        ksl_outputpath,
                        ksl_paramID):
        
        R_automatic_key_strengths_and_limitiations_pdf = ro.r('''
           automaticpdfs <- function(year0, year1, system.filenameout, system.name, var.unit, varname.filenameout, var.name, plevel, p850, p500, p200, p50, workdir, input.path, outdir, ksl_paramID){
                
                ## directory where this script, 'main.Rnw' and 'region.Rnw' are stored: workdir
                ## directory where the pdf with the report will be generated: outdir
                ## path of the input netCDF files with the pre-calculated metrics: input.path

                library(ncdf4) ## to load netCDF files
                library(stringr) ## for manipulating mayuscules in the figure title
                library(knitr)
                library(tools)
                ## plus the compiler 'xelatex' that should be installed in the machine

                options(knitr.duplicate.label = "allow") # To be able to have different iterations of the same child .Rnw file
                
                ## vector of region names to use in figures (might be expanded in future to include more regions):
                ## Beware that the name of the region shown in the scorecards is similar but not the same, as Northern/Shouthern Hemisphere is shortened to NH/SH inside the figures
                region.names <- c("Tropics","Extra-tropical Northern Hemisphere","Extra-tropical Southern Hemisphere")

                ## region names used in the first bullet point (they are slightly longer):
                region.names.bullet1 <- c("Tropics", "Extra-tropical Northern Hemisphere (NH)", "Extra-tropical Southern Hemisphere (SH)")

                ## region names used in the second and subsequent bullet points (they are slightly shorter):
                region.names.bullet2 <- c("Tropics", "Extra-tropical NH", "Extra-tropical SH")

                ## set region borders (the same order in region.names):
                lat.min <- c(-30,30,-90)
                lat.max <- c(30, 90,-30)
                lon.min <- NULL
                lon.max <- NULL
      
                ## select only the first 6 forecast months even if there are 8 in total; last two are forecast months 2-4 and 3-5
                lead.months <- 1:6
                    
                ## for pressure variables, extract their pressure level and their name:
                if(system.filenameout == "ecmwfs5"){system.filenameout_convention <- "ecmwf-5"}
                if(system.filenameout == "meteo_frances6"){system.filenameout_convention <- "meteo_france-6"}
                if(system.filenameout == "meteo_frances7"){system.filenameout_convention <- "meteo_france-7"}
                if(system.filenameout == "cmccs3"){system.filenameout_convention <- "cmcc-3"}
                if(system.filenameout == "dwds2"){system.filenameout_convention <- "dwd-2"}
                if(system.filenameout == "nceps2"){system.filenameout_convention <- "ncep-2"}
                if(system.filenameout == "ukmos14"){system.filenameout_convention <- "uk_met_office-14"}

                if(plevel == "yes"){
                    print("pressure levels")
                    #var.name.inside.pdf <- paste0(var.name, " at ", plevel, " hPa")
                    if(p850=='T' & p500=='T' & p200=='T' & p50=='T'){pr.levels<-c(850, 500, 200, 50)}
                    else if(p850=='T' & p500=='T' & p200=='T' & p50=='F'){pr.levels<-c(850, 500, 200)}
                    else if(p850=='T' & p500=='T' & p200=='F' & p50=='T'){pr.levels<-c(850, 500, 50)}
                    else if(p850=='T' & p500=='F' & p200=='T' & p50=='T'){pr.levels<-c(850, 200, 50)}
                    else if(p850=='F' & p500=='T' & p200=='T' & p50=='T'){pr.levels<-c(500, 200, 50)}
                    else{pr.levels<-c(850, 500, 200, 50)}
                    region_file_to_use <- paste0("_pressure_", length(pr.levels), "levels")    
                    filename.out <- paste('seasonal_monthly_pressure_levels', system.filenameout_convention, varname.filenameout, 'key_strengths_limitations', sep='-')
                }else{
                    print("single levels")
                    #var.name.inside.pdf <- var.name
                    filename.out <- paste('seasonal_monthly_single_levels', system.filenameout_convention, varname.filenameout, 'key_strengths_limitations', sep='-')
                    region_file_to_use <- "_single"
                    pr.levels <- ""
                    print(filename.out)
                }

                if(system.filenameout_convention == "ecmwf-5"){
                    bibliography_file <- 'Add_bibliography'
                }else{
                    bibliography_file <- 'Without_bibliography'
                }
                
                ## Call the sweave 'main' document that will make the automatic report, and generate the pdf.
                ## The R computations are done within the 'child' sweave documents called from main
                ## xelatex is the name of the Latex compiler already installed in our workstations
                ## note that all variables defined in this script will be visible also inside the input .Rnw ('main.Rnw'):
                
                knitr::knit2pdf(input  = paste0(workdir, "/main.Rnw"), output = paste0(outdir, "/", filename.out, ".tex"), compiler='xelatex')
                
                print(paste0('internal files saved at: ', outdir, '/', filename.out, '.pdf'))
                
                return(filename.out)
            }


            ''')

        return R_automatic_key_strengths_and_limitiations_pdf(year0, year1, ksl_centersystem, ksl_centersystemname, ksl_units, ksl_varname, ksl_varname_long, ksl_plevel, p850, p500, p200, p50, workdir, ksl_inputpath, ksl_outputpath, ksl_paramID)

