############################################################
#                                                          #
#      BUILD FINAL CORRECTED MAPS                          #
#                                                          #
############################################################   
############################
##############
#######
library(urbanR)
library(openair)
library(ggplot2)
library(mapview)
library(raster)
library(sp)

#output_path <- "/Users/jan/PhD/STARS_BSC/Test_CALIOPE_Urban/Tests_non_uniform_mesh/"
output_path <- "/esarchive/scratch/nperez/git/Flor/Jan4Nuria/"

#results <- readRDS(paste0(output_path, "test_UniformGrid.rds"))
results <- readRDS(paste0(output_path, "test_NonUniformGrid.rds"))

n_receptors <- nrow(results[results$date == results$date[1],])
crs_sim <- "+proj=utm +zone=31 +ellps=intl +units=m +no_defs"


mean_map <- results[results$date == results$date[1],]
######
## Create uniform mes:I
#receptor_grid <- sf::st_sf(geom=sf::st_make_grid(spatial_context, cellsize = config$sp_res, what = "centers"), crs=config$crs_sim)

############################################################
#                      Plot mean                           #
############################################################ 
mean_map_sf <- mean_map %>% sf::st_as_sf(coords = c("X", "Y"), crs = crs_sim)

bcn_mean_map <- mean_map_sf 
bcn_mean_map$X <- sf::st_coordinates(bcn_mean_map)[,1]
bcn_mean_map$Y <- sf::st_coordinates(bcn_mean_map)[,2]


###### lat-lon
#bcn_mean_map <- sf::st_transform(bcn_mean_map,crs("+proj=longlat"))
#bcn_mean_map$X <- sf::st_coordinates(bcn_mean_map)[,1]
#bcn_mean_map$Y <- sf::st_coordinates(bcn_mean_map)[,2]
#points <- sp::SpatialPoints(methods::as(bcn_mean_map[,c('X','Y')], "Spatial"), proj4string = sp::CRS("+proj=longlat"))

## write to netcdf 
#library(ncdf4)
#writeRaster(mean_raster, filename=paste0(output_path,"map_mean.nc"), format="CDF", overwrite=TRUE)   

points <- sp::SpatialPoints(methods::as(bcn_mean_map[,c('X','Y')], "Spatial"), proj4string = sp::CRS(crs_sim))
pixels <- sp::SpatialPixelsDataFrame(points,tolerance = 0.99, as.data.frame(bcn_mean_map[,"NO2"]))
mean_raster <- raster::raster(pixels[,'NO2'])


plot(mean_raster,
     maxpixels=5000000, 
     col=colorRampPalette(rev(rainbow(4)))(200),
     useRaster=TRUE,
     interpolate=TRUE,
     axes=FALSE,
     legend.width = 1.5,
     legend.mar = 8,
     legend.args = list(text = expression(paste("NO2 [", mu, "g/",m^3,"]")), side = 3, line = 1),
     alpha=0.85)
scalebar(2000, xy = c(434000, 4574812), type = 'bar',label=c(0,1,2),below="km")

