# 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])
par(mar = c(0.5,5,1,5), xpd = TRUE)
plot(shp_herding)
for (i in 1:31) {
text(x = shp_herding@polygons[[i]]@labpt[1], y = shp_herding@polygons[[i]]@labpt[2], 
     label = shp_herding@data[i,3], col = 'blue')
}
labels <- paste(shp_herding@data[,3], 
                shp_herding@data[par(mar = c(0.5,5,1,5), xpd = TRUE)
plot(shp_herding)
for (i in 1:31) {
text(x = shp_herding@polygons[[i]]@labpt[1], y = shp_herding@polygons[[i]]@labpt[2],
     label = shp_herding@data[i,3], col = 'blue')
}
labels <- paste(shp_herding@data[,3],       
                shp_herding@data[,4])
legend(x = 16.5, y = 70.2,
       legend = labels[1:31],
       bty = 'n')
,4])
legend(x = 16.5, y = 70.2, 
       legend = labels[1:31], 
       bty = 'n')



# 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()

poly <- list()
  for (pol in sel_IDs[,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, "positions.RDS")) 
}

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[which(data2 < 1000)] = 0

positions <- list()
for (i in 1:length(sel_IDs[,1])) {
  pos <- readRDS(paste0(sel_IDs[i,1], "positions.RDS"))[[1]]
positions <- append(positions, list(pos))
  data2[-pos] <- sel_IDs[i,1]
}
test <- 1:(prod(dim(data2)))
test <- lapply(positions, function(x) {test[!(test %in% x)]})
for(j in 1:31) { 
  for (i in 1:31) {
    if (any(test[[j]] %in% test[[i]])) {
      print(c(i,j))
    }
  }
} 

  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_Herding_mask.RDS")


mask <- readRDS(file = "FMI_Herding_mask.RDS")
tas <- mask$mask
xs <- mask$x
ys <- mask$y
s2dv::PlotEquiMap(tas, lon = xs, lat = ys, filled.c =F)
tas.masked <- tas
tas.masked[which(t(data2) == 0)] <- NA
s2dv::PlotEquiMap(tas.masked, lon = xs, lat = ys, filled.c = F)


