rm(list=ls())
library(startR)
library(multiApply)
library(s2dv)
library(rgdal)
library(plyr)
library(ggplot2)
library(maptools)
library(rgeos)


path <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/climatology'
setwd(path)

vars <- c('tasmax', 'tasmin', 'tas', 'prlr')
brks_var <- data.frame(tasmax = seq(-13, 23, 4),
                       tasmin = seq(-13, 23, 4),
                       tas = seq(-13, 23, 4),
                       prlr = seq(0, 90, 10))
freq <- rep('monthly_mean', 4)

lat_rovanievi <- 66.5
lon_rovanievi <- 25.5
reference_period <- 1999:2020

# --------------------------------------- NUTS
path2 <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/region_exploration'
# NUTS2
mask.file <- paste0(path2, '/NUTS2/ref-nuts-2021-20m.shp/NUTS_RG_20M_2021_4326_LEVL_2.shp/NUTS_RG_20M_2021_4326_LEVL_2.shp')
shp <- rgdal::readOGR(mask.file)

#subset region for Scandinavia
lat_min <- 65
lat_max <- 72
lon_min <- 13
lon_max <- 33

library(RColorBrewer)
pals <- brewer.pal(9, 'Reds')[3:9]
pals <- c("#ffffb3",pals,'#525252')

gusa <- map_data("world")

# NUTS0 to plot country borders
mask.file_0 <- paste0(path2, '/NUTS2/ref-nuts-2021-20m.shp/NUTS_RG_20M_2021_4326_LEVL_0.shp/NUTS_RG_20M_2021_4326_LEVL_0.shp')
shp_0 <- rgdal::readOGR(mask.file_0)

mask.file_3 <- paste0(path2, '/NUTS3/NUTS_RG_60M_2021_4326.shp/NUTS_RG_60M_2021_4326.shp')

shp_3 <- rgdal::readOGR(mask.file_3)
shp_3 <- subset(shp_3, CNTR_CODE == "FI")
shp_3 <- subset(shp_3, NUTS_ID %in% paste0("FI1D", c(1:3,5,7:9)))
Lappi <- subset(shp_3, NUTS_NAME == "Lappi")
NoLappi <- subset(shp_3, NUTS_NAME != "Lappi")
shp_FI <- subset(shp, CNTR_CODE == "FI")
shp_FI <- subset(shp_FI, NUTS_ID != "FI1D")
mask.file_4 <- paste0(path2, '/LAU/LAU_RG_01M_2020_4326.shp')

shp_4 <- rgdal::readOGR(mask.file_4)
shp_4 <- subset(shp_4, CNTR_CODE == "FI")

muni2 <- c('047', '148', '240', '320', '241', '261', '273', '498', '583', '854',
          '614', '683', '698', '732', '742', '751', '758', '845', '851', '890', '976')

shp_muni2 <- subset(shp_4, LAU_ID %in% muni2)
#n <- 21
#qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
#col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
#plot(shp_muni2, col = col_vector)
#legend('topleft', legend = shp_muni2@data$LAU_NAME, fill = col_vector, bty = 'n')




# -----------------------------------------------

vars_rovanievi <- c()
for (v in 1:length(vars)) {
  data <- startR::Start(
     dat = paste0("/esarchive/recon/ecmwf/era5/monthly_mean/$var$_f1h-r1440x721cds/$var$_$year$$month$.nc"),
               var = vars[v],
               year = as.character(reference_period),
               month = sprintf("%02d", 1:12),
               time = 'all',
               lat = startR::values(list(50, 80)),
               lon = startR::values(list(10, 35)),
               synonims = list(lat = c('lat', 'latitude'),
                               lon = c('lon', 'longitude')),
               num_procs = 1,
               return_vars = list(lat = NULL, lon = NULL),
               retrieve = TRUE)
print(vars[v])
print(as.vector(attributes(data)$NotFound)[which(!is.na(attributes(data)$NotFound))])

  if (vars[v] != 'prlr') {
    clim <- drop(Apply(list(data), list('year'), fun = mean, na.rm = T)$output)
    clim <- clim - 273.15
  } else {
    clim <- drop(Apply(list(data), list('year'), fun = sum, na.rm = T)$output)
    clim <- clim * 86400 * 1000
  }

print(range(clim))
  coord <- data.frame(x = sort(rep(attributes(data)$Variables$common$lon,
                                 length(attributes(data)$Variables$common$lat))),
                      y = rep(attributes(data)$Variables$common$lat,
                            length(attributes(data)$Variables$common$lon)))

  # Monthly:
  data_rovanievi <- c()
  brks_labels <- apply(brks_var[,v], function(x) {
                    paste0("(", x 
  for (m in 1:12) {
    data.df <- data.frame(data = as.vector(clim[m,,]),
                          long = sort(rep(attributes(data)$Variables$common$lon,
                                 length(attributes(data)$Variables$common$lat))),
                          lat = rep(attributes(data)$Variables$common$lat,
                                 length(attributes(data)$Variables$common$lon)))
    data_rovanievi <- c(data_rovanievi,
                        subset(data.df, long == 25.5 & lat == 66.5)[,1])
    data.sp <- SpatialPointsDataFrame(coord, data = data.df)
    proj4string(data.sp) <- proj4string(shp_3)

    Lappi <- gIntersection(data.sp, Lappi)


    pos <- c()
    for (i in 1:nrow(Lappi@coords)) {
      for (j in 1:nrow(data.sp@coords)) {
        if (all(Lappi@coords[i,] == data.sp@coords[j, ])) {
          pos <- c(pos, j)
        }
      }
    }
    res <- data.sp[pos, ]
    brks <- brks_var[, v]
    month <- month.name[m]
ggplot(data = res@data) +
  geom_polygon(aes(long, lat, group = group), fill = "darkgrey", data = gusa) +
  # cut region:
  coord_map(projection = "stereographic",
            xlim = c((lon_min + 7),(lon_max - 2)),
            ylim = c((lat_min),(lat_max))) +
  geom_polygon(aes(x = long, y = lat, group = group),
               color = "white", fill = 'grey',  size = 0.08, data = shp_FI) +
  geom_polygon(aes(x = long, y = lat, group = group),
               color = "white", fill = 'lightgrey',  size = 0.08, data = NoLappi) +
  # add borders: 
  geom_polygon(aes(long, lat, group = group), fill = NA, data = shp_0,
               color = "black", size = 0.1) +
  geom_polygon(aes(long, lat, group = group), fill = NA, data = shp_muni2,
               color = "black", size = 0.1) +
  geom_point(aes(long, lat, color = cut(data, breaks = brks))) +
  geom_point(aes(y = 66.5039, x= 25.7294), pch = 1, colour = 'blue') +
  # edit legend
  theme_bw() +                                                                                          # Theme black and white
  scale_colour_manual(values = rev(heat.colors(9)), #limits = brks,
                      #breaks = brks,
                   label = c("(-13, -9]", "(-9, -5]", 
                             "(-5, -1]", "(-1, 3]",
                              "(3, 7]", "(7, 11]",
                              "(11, 15]", "(15, 19]", "(19, 23]"), 
                    name = '', drop = FALSE) +
  theme(panel.background = element_rect(fill = 'azure'),
        text = element_text(family = "Times")) +  # Colour of ocean
  xlab('Longitude') + ylab('Latitude') +
  scale_x_continuous(breaks = seq(-15, 45, 5),labels = waiver()) +
  scale_y_continuous(breaks = seq(30, 70, 5),labels = waiver()) +
  ggtitle(paste(month, vars[v], 'ERA5 1999-2020')) +
  ggsave(paste0("Rovanievi_", month,"1999-2020_ERA5_NUTS3_", vars[v], "_clim.png"),
                 width = 8, height = 8, units = 'cm')
  }
print(range(data_rovanievi))
  vars_rovanievi <- cbind(vars_rovanievi, data_rovanievi)
}

par(mar = c(5.5, 4, 4, 4))
matplot(1:12, vars_rovanievi[,1:3], type = 'l', xaxt = 'n',
        col = c('darkred', 'darkblue', 'orange'), xlab = '',
        ylab = 'temperature (degreesC)',
        main = paste('Rovanievi Climatology',
                     paste(range(reference_period), collapse = '-')))
par(new = TRUE)
plot(1:12, vars_rovanievi[,4], type = 'h', xaxt = 'n', yaxt = 'n',  ylab = '',
     lwd = 3, col = 'darkgreen', xlab = '')
axis(side = 4, at = pretty(range(vars_rovanievi[,4])))
mtext("Total precipitation (mm)", side=4, line = 3)
axis(1, 1:12, month.name, las = 2)
legend('topleft', vars, col = c('darkred', 'darkblue', 'orange', 'darkgreen'),
       pch = 16, bty = 'n')
 
