rm(list=ls())

library(maptools)
library(CSTools)
library(s2dv)
library(ragg)
library(multiApply)
library(startR)
library(sf)
library(rgeos)
library(multiApply)
library(lubridate)
library(ClimProjDiags)
working_dir <- "/esarchive/scratch/nperez/git/Flor/ArticXchange/"
output_dir <- "/esarchive/scratch/nperez/ArticXChange/"
setwd(working_dir)

mask_fmi <- readRDS(paste0(working_dir, "masks/FMI_Herding_mask.RDS"))
polys <- unique(as.vector(mask_fmi$mask))[-1]
dim(polys) <- c(poly = length(polys))

fmi_clim <- readRDS("FMI_herding_monthly_clim_polygons.RDS")

mask.file_4 <- paste0('region_exploration/LAU/LAU_RG_01M_2020_4326.shp')
shp_4 <- rgdal::readOGR(mask.file_4)
shp_4 <- subset(shp_4, CNTR_CODE == "FI")
## shp_herding <- subset(shp_4, as.numeric(LAU_ID) %in% polys) # R4.1 used to work
# R3.6.1:
shp_herding <- subset(shp_4, LAU_ID %in% sprintf("%03d", polys))
# Subset region
lat_min <- 64#59
lat_max <- 71
lon_min <- 20
lon_max <- 31

year <- 2020
mes <- 6

fmi_clim_m <- subset(fmi_clim, mon == mes)

path <- "/esarchive/obs/fmi/climgrid/monthly_mean/$var$/$var$_$year$$month$.nc"

tas <- Start(dat = path,
             var = 'tas',
             year = as.character(year),
             month = sprintf("%02d", mes),
             y = 'all',
             x = 'all',
             synonims = list(y = c('y', 'lat', 'latitude'),
                             x = c('x', 'lon', 'longitude')),
             return_vars = list(y = NULL, x = NULL),
             retrieve = TRUE)

ys <- attributes(tas)$Variable$common$y
xs <- attributes(tas)$Variable$common$x

tas_polys <- Apply(list(tas, mask_fmi$mask, polys),
                   target_dims = list(c('x', 'y'), c('x', 'y'), NULL),
                   function(x, y, z) {
                     mean(x[which(y == z)], na.rm = TRUE)},
                   ncores = 6)$output1
tas_polys <- tas_polys[1,1,,,match(shp_herding@data$LAU_ID, sprintf("%03d", polys))]


library(sf)
library(ggplot2)
#library(ggplot2, lib.loc = .libPaths()[2])
library(RColorBrewer)
library(rgeos)

gusa <- map_data("world")

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

brks <- 0:5
brks <- seq(258, 274, 2)

plot_poly <- list()
polys_data <- NULL


## Now fill each polygon with the mean value
  data_pol <- data.frame(data = tas_polys - 273.15,
                         LAU_ID = shp_herding@data$LAU_ID)
  shp_data <- merge(shp_herding, data_pol, by.x="LAU_ID", by.y="LAU_ID")

# Magic lines below that converts SpatialPolygonsDataFrame to normal data frame
  shp_data@data$id <- rownames(shp_data@data)
  df.points <- fortify(shp_data, region = "id")
  df.df <- plyr::join(df.points, shp_data@data, by = "id")
ano <- df.df
ano$data <- ano$data - fmi_clim_m$data

ggplot(data = ano) + #df.df) +
        geom_polygon(aes(long, lat, group = group),fill = "lightgrey", data = gusa) +
        coord_map(projection = "stereographic",
                  xlim = c(lon_min, lon_max),
                  ylim = c(lat_min, lat_max)) +
       # geom_polygon(aes(x = long, y = lat, fill = cut(data, breaks = seq(-14, 18, 2)),
        geom_polygon(aes(x = long, y = lat, fill = cut(data,
                         breaks = seq(0, 5, 0.5)),
             group = group), color = "grey",size = 0.08) +
        geom_polygon(aes(x = long, y = lat, group = group), fill = NA,
                    color = "grey", size = 0.5, data = shp_herding) +
        theme_bw() + 
        scale_fill_manual(values = c(#rev(brewer.pal(9, 'Blues')),
                                     'white', brewer.pal(9, 'Reds'), "black"),
                          drop = FALSE, name = 'tas(ºC)') +
        theme(panel.background = element_rect(fill = 'azure'),
              text = element_text(family = "Times")) +  # Colour of ocean
        xlab('Longitude') + ylab('Latitude') +
        scale_x_continuous(breaks = seq(-12, 45, 4),labels = waiver()) +
        scale_y_continuous(breaks = seq(32, 70, 4),labels = waiver()) +
        ggtitle(paste(month.name[mes], year))# +

