library(startR)
obs_path <- list(name = "FMI",
                 path = "/esarchive/obs/fmi/climgrid/monthly_mean/$var$/$var$_$sdate$$ftime$.nc")
tas_ref <- Start(dat = obs_path,
             var = 'tas',
             sdate = as.character(1993),
             ftime = sprintf('05'),
             y = indices(1:60),
             x = 'all',
             synonims = list(y = c('y', 'lat', 'latitude'),
                             x = c('x', 'lon', 'longitude'),
                             ftime = c('ftime', 'time')),
             return_vars = list(y = NULL, x = NULL),
             retrieve = TRUE)
ys <- attributes(tas_ref)$Variable$common$y
xs <- attributes(tas_ref)$Variable$common$x

tas_ref <- t(tas_ref[1,1,1,1,,])
names(dim(tas_ref)) <- c('x', 'y')

library(maptools)

mask.file <- paste0("/esarchive/shapefiles/",
  'NUTS/ref-nuts-2021-20m.shp/NUTS_RG_20M_2021_4326_LEVL_2.shp/NUTS_RG_20M_2021_4326_LEVL_2.shp')
shp_eu <- rgdal::readOGR(mask.file)
shp_fi <- subset(shp_eu, CNTR_CODE == "FI")
##     plot(shp_fi)
#LAUS
mask.file_laus <- paste0("/esarchive/shapefiles/", '/LAU/LAU_RG_01M_2020_4326.shp')
shp_laus <- rgdal::readOGR(mask.file_laus)
shp_laus <- subset(shp_laus, CNTR_CODE == "FI")
Laus_lapland <- c('047', '148', '240', '320', '241', '261',
                  '273', '498', '583', '854',
                  '614', '683', '698', '732', '742', '751',
                  '758', '845', '851', '890',
                  '976')
shp_lapland <- subset(shp_laus, LAU_ID %in% Laus_lapland)

#    res <- ShpCutArray(tas_ref, xs, ys, shp_lapland)

# Take an array[x,y], x y coords from FMI gridded dataset and shp_lappland
# returns a data.frame
ShpCutArray <- function(array, xs, ys, shp) {
  library(sf)
  library(rgeos)
  library(ggplot2)
  if (all(names(dim(array)) != c('x', 'y'))) {
    stop("The dimensions order in parameter 'array' is expected x,y")
  } 
  df <- data.frame(dat = as.vector(array),
                   XCoord = rep(xs, length(ys)),
                   YCoord = sort(rep(ys, length(xs)), decreasing = TRUE))
  df <- df[which(!is.na(df[,1])),]
  sf <- st_as_sf(df, coords = c("XCoord", "YCoord"), crs = 'EPSG:3067')
##       maptools::plot(df)
  my_latlon_df <- st_transform(sf, 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)
  sp <- SpatialPointsDataFrame(coord,
                               data = data.frame(my_latlon_df$dat))
  proj4string(sp) <- proj4string(shp) #shp_lappland
  # coordenadas intersección:
  data_pol  <- c()
  for (pol in shp@data$FID) { # Loop polygons
    shp_pol <- subset(shp, FID == pol)
    shp_pol <- gIntersection(sp, shp_pol)

    pos <- c()
    for (i in 1:nrow(shp_pol@coords)) { # Loop coordinates in the polygon
      for (j in 1:nrow(sp@coords)) { # Loop coordinates in data
        if (identical(all.equal(shp_pol@coords[i,], sp@coords[j,]), TRUE)) {
          pos <- c(pos, j)
        }
      }
    }
    data <- sp[pos,]
    data2 <- cbind(dat = data, FID = rep(pol, nrow(data)))
    colnames(data2@data) <- c('dat', 'FID')
    if (pol == 'FI_583') { # This condition initializes data_byFID
      data_byFID <- data2
    } else {
      data_byFID <- rbind(data_byFID, data2)
    }
    data_pol <- c(data_pol, mean(data$my_latlon_df.dat))
  }
  
  data_byFID_df <- cbind(data_byFID@data, data_byFID@coords)
  data_pol <- data.frame(data = data_pol, LAU_ID = shp@data$LAU_ID)
  shp_data <- merge(shp, data_pol, by.x="LAU_ID", by.y="LAU_ID")
  # Magic lines below that converts SpatialPolygonsDataFrame to normal data frame
  shp_data@data$id <- rownames(shp_data@data)
  df.points <- fortify(shp_data, region = "id")
  df.df <- plyr::join(df.points, shp_data@data, by = "id")
}
