# 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 FMI map
library(startR)
path <- "/esarchive/obs/fmi/climgrid/monthly_mean/$var$/$var$_$year$$month$.nc"

tas <- Start(dat = path,
             var = 'tas',
             year = as.character(2020),
             month = sprintf("%02d", 1),
             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

# 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),
                     XCoord = rep(xs, length(ys)),
                     YCoord = sort(rep(ys, length(xs)), decreasing = TRUE))
#tas_df <- tas_df[which(!is.na(tas_df[,1])),]
tas_sf_df <- st_as_sf(tas_df, coords = c("XCoord", "YCoord"), crs = 'EPSG:3067')
##       plot(tas_sf_df)
my_latlon_df <- st_transform(tas_sf_df, crs = 4326)
my_latlon_df <- my_latlon_df%>%
dplyr::mutate(long = st_coordinates(my_latlon_df)[,1],
                lat = st_coordinates(my_latlon_df)[,2])

coord <- data.frame(x = my_latlon_df$long, y = my_latlon_df$lat)
tas.sp <- SpatialPointsDataFrame(coord,
                                   data = data.frame(my_latlon_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, my_latlon_df.tas == 1))
data2 <- t(tas[1,1,1,1,,])
data2[pos] <- 0
data2[-pos] <- 1
image(as.vector(xs), sort(as.vector(ys)), data2)
s2dv::PlotEquiMap(data2, lon = xs, lat = ys, filled.c=F)
names(dim(data2)) <- c('x', 'y')
setwd("/esarchive/scratch/nperez/git/Flor/ArticXchange/masks/")
saveRDS(list(mask = data2, x = xs, y = ys), file = "FMI_Lapland_mask.RDS")


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

