# original author Bala:
rm(list=ls())
library(abind)
library(multiApply)
library(s2dv)
library(s2dverification)
library(rgdal)
library(plyr)
library(ggplot2)
library(maptools)

path <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/region_exploration'
setwd(path)
var <- readRDS(file = 'data4nuts.Rds')

x <- var$x
lat <- var$lat
lon <- var$lon

mask.file <- paste0(path, '/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)
country <- substring(as.character(shp$NUTS_ID), 1, 4)

mask.file_0 <- paste0(path, '/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)

mydata <- data.frame(NUTS_ID=unique(shp$NUTS_ID), value= x)

#Join mydata with mapdata
df <- merge(shp, mydata, by.x="NUTS_ID", by.y="NUTS_ID")
df0 <- shp_0

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

#NUTS0
df0@data$id <- rownames(df0@data)
df0.points <- fortify(df0, region="id")
df0.df0 <- join(df0.points, df0@data, by="id")

# After this.. plotting

lat_min <- 32
lat_max <- 73
lon_min <- -15
lon_max <- 44

xmin<- lon_min
xmax<- lon_max
ymin<- lat_min
ymax<- lat_max

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

#brk <- c(-1,0.5,20,40,60,80,100)
brk <- c(-1,0.5,10,20,30,40,50,60,70,80,90,100)

gusa <- map_data("world")

ggplot(data = df.df) + 
  geom_polygon(aes(long, lat, group = group),fill = "lightgrey", data = gusa) +                              # Adding grey color to the regions with no data
  geom_polygon(aes(x = long, y = lat, fill = cut(value, breaks = brk), group = group),                  # Plotting the data in polygon
               color = "grey",size = 0.08) +
  geom_polygon(aes(long, lat, group = group),fill = NA, data = df0.df0, color = "black", size=0.1) +   # Plotting the grey country profile
  coord_map(projection = "stereographic",xlim = c((xmin+7),(xmax-2)), ylim = c((ymin+4),(ymax-4))) +                                 # Fixing coordinates            
  theme_bw() +                                                                                          # Theme black and white
  scale_fill_manual(values=pals, label=c('No events','10%-20%','20%-30%','30%-40%','40%-50%','50%-60%','60%-70%','70%-80%','80%-100%'), name='') +
  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, 10),labels = waiver()) +
  scale_y_continuous(breaks = seq(30, 70, 10),labels = waiver()) +
  ggtitle('')
