# Create a .RDS to select FMI points in Lapland

# Step 1: Load the shapefile containing Laplan region definition
library(sf)
library(rgeos)
path <- '/esarchive/shapefiles/'
mask.file_3 <- paste0(path, '/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)))
shp_lap <- subset(shp_3, NUTS_NAME == 'Lappi')
subregions <- shp_3$NUTS_ID
shp_lap <- subset(shp_3, NUTS_NAME == 'Lappi')
plot(shp_lap)

# 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 <- 65#59
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:
data_pol  <- c()
shp_pol <- gIntersection(tas.sp, shp_lap)

pos <- c()
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)
    }
  }
}
data <- tas.sp
nas <- which(is.na(data$my_latlon_df.tas))
data[pos, ] <- 0
data[-pos, ] <- 1
data[nas,] <- NA
plot(subset(data, tas_df.tas == 1))
data2 <- t(tas[1,1,1,1,,])
data2[pos] <- 0
data2[-pos] <- 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_Lapland_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)

