library(raster)
library(geosphere)
library(sp)
library(sf)
library(mapview)
library(leaflet)
#library(tidyverse)

##############################################################################
#			Function to create de raster of reference
##############################################################################
ref_raster <- function (my_res_lat, my_res_lon, my_aoi, crs) 
{
  print(paste0("Calculate number of rows and columns for raster file"))
  extent_distance_vertical <- geosphere::distm(c(raster::extent(my_aoi)[1], 
                                                 raster::extent(my_aoi)[3]), c(raster::extent(my_aoi)[1], raster::extent(my_aoi)[4]), 
                                               fun = geosphere::distHaversine)
  
  vertical_mid_distance <- (raster::extent(my_aoi)[4] - raster::extent(my_aoi)[3])/2
  lat_mid <- raster::extent(my_aoi)[3] + vertical_mid_distance
  horizontal_distance <- raster::extent(my_aoi)[2] - raster::extent(my_aoi)[1]
  
  if (horizontal_distance > 180) {
    one_degree_horizontal_distance <- geosphere::distm(c(1, 
                                                         lat_mid), c(2, lat_mid), fun = geosphere::distHaversine)
    extent_distance_horizontal <- one_degree_horizontal_distance * 
      horizontal_distance
  }else {
    extent_distance_horizontal <- geosphere::distm(c(raster::extent(my_aoi)[1], 
                                                     lat_mid), c(raster::extent(my_aoi)[2], lat_mid), fun = geosphere::distHaversine)
  }
  ncol_rast <- as.integer(extent_distance_horizontal/my_res_lon)
  nrow_rast <- as.integer(extent_distance_vertical/my_res_lat)
  print(paste0("Create raster file from points"))
  rast <- raster::raster(nrows = nrow_rast, ncols = ncol_rast,
                         crs = as.character(raster::crs(crs)), vals = 0, ext = raster::extent(my_aoi))
  
  return(rast)
}
#######################################################################################

#load data
my_res_lat <- 100
my_res_lon <- 100
load('/esarchive/scratch/ccampos/raster_ref_data/my_aoi.RData')
#caliope <- nc_open('/home/abarrant/Documents/AQS/sconcno2_2022010100.nc')

caliope_annual <- '/esarchive/scratch/abarrant/shp_output/sconcno2/2023/amean_sconcno2_2023-01-01_2023-12-31.nc'
raster_caliope <- raster(caliope_annual)
projection(raster_caliope) <- CRS("+proj=lcc +lat_0=40 +lon_0=-3 +lat_1=43. +lat_2=37. +datum=WGS84")

crs_latlon <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +no_defs +towgs84=0,0,0"
crs_utm <- "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs"
raster_caliope <- projectRaster(raster_caliope, crs=crs_latlon)
#mapview(raster_caliope)


#modify my_aoi to cover caliope
#ymin <- extent(raster_caliope)@ymin
#my_poligon <- st_geometry(my_aoi_v2)[[1]][[1]]
#my_poligon[c(1,4,5),2] <- rep(ymin,3)

#sfc <- st_sfc(st_polygon(list(my_poligon)))#, epsg=4326)
#st_crs(sfc) <- st_crs(my_aoi_v2)

#my_aoi <- my_aoi_v2
#st_geometry(my_aoi) <- sfc

#executing the function
raster_ref_caliop <- ref_raster(my_res_lat, my_res_lon, my_aoi, crs=crs_latlon)

#alignment ---------------------------------------------------------------------
raster_ref_aligned <- projectRaster(
  from = raster_ref_caliop,
  crs = crs(raster_caliope),
  method = "bilinear"  # or "ngb" if categorical data
)

#align the extent while maintaining the high resolution
#calculate the adjustment needed for alignment
res_ref <- res(raster_ref_aligned)
res_cal <- res(raster_caliope)
origin_ref <- bbox(raster_ref_aligned)[, 1] %% res_ref
origin_cal <- bbox(raster_caliope)[, 1] %% res_cal

#calculate the shift needed
shift_x <- (origin_cal[1] - origin_ref[1]) %% res_cal[1]
shift_y <- (origin_cal[2] - origin_ref[2]) %% res_cal[2]

#create a new extent with alignment correction
e <- extent(raster_ref_aligned)
e@xmin <- e@xmin + shift_x
e@xmax <- e@xmin + (ncol(raster_ref_aligned) * res_ref[1])
e@ymin <- e@ymin + shift_y
e@ymax <- e@ymin + (nrow(raster_ref_aligned) * res_ref[2])

#apply the new extent
raster_ref_aligned <- setExtent(raster_ref_aligned, e)
raster_ref_caliop_100m <- raster_ref_aligned
save(raster_ref_caliop, file='/esarchive/scratch/abarrant/geo/raster_ref_caliop_100m.RData')
