# Create a .RDS to select FMI points in Lapland

# Step 1: Load the shapefile containing Laplan region definition
library(sf)
library(rgeos)

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

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")

sel_IDs <- read.table("../region_exploration/LAUS_IDs_selected.csv")
shp_herding <- subset(shp_4, as.numeric(LAU_ID) %in% sel_IDs[,1])


# Step 2: Load 1 ERA5Land map
library(startR)
path <- "/esarchive/recon/ecmwf/era5land/monthly_mean/$var$_f1h/$var$_$year$$month$.nc"

# Subset region
lat_min <- 64#65
lat_max <- 71
lon_min <- 20
lon_max <- 31

tas <- Start(dat = path,
             var = 'tas',
             year = as.character(2020),
             month = sprintf("%02d", 1),
             latitude = values(list(lat_min, lat_max)),
             latitude_reorder = Sort(),
             longitude = values(list(lon_min, lon_max)),
             longitude_reorder = CircularSort(-180, 180),
             synonims = list(latitude=c('lat','latitude'),
                             longitude=c('lon','longitude')),
             return_vars = list(lon = NULL, lat = NULL),
             retrieve = TRUE)

lat <- attributes(tas)$Variable$common$lat
lon <- attributes(tas)$Variable$common$lon



# Step 2: Transform it to data.frame with correct projection

tas_df <- data.frame(tas = as.vector(t(tas[1,1,1,1,,]) - 273.15),
                       long = rep(lon, length(lat)),
                       lat = sort(rep(lat, length(lon)), decreasing = FALSE))



coord <- data.frame(x = tas_df$long, y = tas_df$lat)
tas.sp <- SpatialPointsDataFrame(coord,
                                   data = data.frame(tas_df$tas))

proj4string(tas.sp) <- proj4string(shp_lap)
# coordenadas intersección:
poly <- list()
  for (pol in sel_IDs[-c(22,24,25,28:31),1]) {
  pos <- c()
  shp_pol <- subset(shp_herding, as.numeric(LAU_ID) == pol)
  shp_pol <- gIntersection(tas.sp, shp_pol)
    for (j in 1:nrow(tas.sp@coords)) { # Loop coordinates in data
      for (i in 1:nrow(shp_pol@coords)) { # Loop coordinates in the polygon
   #    for (j in 1:nrow(tas.sp@coords)) { # Loop coordinates in data
        if (identical(all.equal(shp_pol@coords[i,],
                                tas.sp@coords[j,]), TRUE)) {
            pos <- c(pos, j)
        }
      }
    }
    poly <- append(poly, list(pos))
    saveRDS(list(pos, pol), file = paste0(pol, "positionsERA5.RDS"))
}

short_file <- readRDS(paste0(sel_IDs[1,1], "positionsERA5.RDS"))
long_file <- readRDS(paste0(sel_IDs[22,1], "positionsERA5.RDS"))


data2 <- t(tas[1,1,1,1,,])
data2[,] <- 0
for (i in 1:length(sel_IDs[,1])) {
  pos <- readRDS(paste0(sel_IDs[i,1], "positionsERA5.RDS"))[[1]]
  data2[-pos] <- sel_IDs[i,1]
}

image(lon, lat, data2)
s2dv::PlotEquiMap(data2, lon = lon, lat = lat, filled.c=F)
names(dim(data2)) <- c('lon', 'lat')
setwd("/esarchive/scratch/nperez/git/Flor/ArticXchange/masks/")
saveRDS(list(mask = data2, lon = lon, lat = lat), file = "ERA5_Herding_mask.RDS")


s2dv::PlotEquiMap(tas, lon = lon, lat = lat, filled.c =F)
tas.masked <- tas
tas.masked[which(t(data2) != 1)] <- NA
s2dv::PlotEquiMap(tas.masked, lon = lon, lat = lat, filled.c = F)

