###############################################################
#                                                             #
# Step-by-Step Script to Calculate Traffic Density buffers    #                                                             #
#                                                             #
###############################################################


# Load necessary libraries
library(sf)
library(sp)
#library(mapview)
library(dplyr)


#print(paste0("Pollutant: ",pollutant, ", Start date: ",start_day,", End date: ",end_day,
#             ", Input path: ", path_save, ", Output_path: ", path_nc, ", Add borders: ", shp_cat ))


# Load traffic data
wdir <- "/esarchive/scratch/ajulian/datasets_MPCS/Results"
wdir2 <- "/esarchive/scratch/ajulian/scripts/Open_Data/Traffic_buffers/Results"
traffic_ind <- readRDS(file.path(wdir, "data_cat_traffic_bcn.RDS"))

# Load domain and grid
spatial_context <- readRDS(file.path(wdir2, def_domini)) #"def_domini_bcn.RDS"
refined_grid_sf <- readRDS(file.path(wdir2, def_refined))
crs_utm    <- "+proj=utm +zone=31 +ellps=intl +units=m +no_defs"   
crs_latlon <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"  



##########
# Transform traffic_ind to UTM (zone 31N)
traffic_ind_sf <- sf::st_as_sf(traffic_ind, coords = c("lon", "lat"), crs = crs_spatial_context)
traffic_ind_sf <- sf::st_transform(traffic_ind_sf, crs_utm)
spatial_context <- sf::st_transform(spatial_context, crs_utm)

# Perform the intersection
traffic_ind_info <- sf::st_intersection(traffic_ind_sf, spatial_context)

#mapview(traffic_ind_info, zcol = "indice_dens_trafico")

# Select only the indice_dens_trafico and geom columns
traffic_ind_info <- traffic_ind_info %>%
  dplyr::select(indice_dens_trafico, geom)

traffic_ind_info_sf <- sf::st_transform(traffic_ind_info, crs_utm)

###########
# Make Buffers
###########

traffic_density_index <- function(refined_grid_sf, buffer) {
    sf_buffers <- sf::st_buffer(refined_grid_sf, dist=buffer)
    traffic_density_index <- numeric()
    sf_buffers <- st_transform(sf_buffers,crs_utm)
    for(i in 1:nrow(sf_buffers)){
        roads_context <- sf::st_intersection(traffic_ind_sf, sf_buffers[i,])
        lengths <- sf::st_length(roads_context)
        class(lengths) <- setdiff(class(lengths), "units")
        lengths <- as.numeric(lengths) # Convert to meters
        traffic_density_index[i] <- sum(roads_context$indice_dens_trafico * lengths)
    }
    return(traffic_density_index)
}

area_type <- "buffer"
traffic_buffers <- refined_grid_sf

buffer <- 500
traffic_buffers$buffer_500m <- traffic_density_index(refined_grid_sf, buffer)
buffer <- 100
traffic_buffers$buffer_100m <- traffic_density_index(refined_grid_sf, buffer)

#mapview::mapview(traffic_buffers, zcol = "buffer_100m")

#Save the data


#mapview::mapview(buffers, zcol = "buffer_500m")

#Normalization of the traffic density index

min_value_100 <- min(traffic_buffers$buffer_100m, na.rm = TRUE)
max_value_100 <- max(traffic_buffers$buffer_100m, na.rm = TRUE)
min_value_500 <- min(traffic_buffers$buffer_500m, na.rm = TRUE)
max_value_500 <- max(traffic_buffers$buffer_500m, na.rm = TRUE)
traffic_buffers$buffer_100m_normalized <- (traffic_buffers$buffer_100m - min_value_100) / (max_value_100 - min_value_100) * 100
traffic_buffers$buffer_500m_normalized <- (traffic_buffers$buffer_500m - min_value_500) / (max_value_500 - min_value_500) * 100

# Plot the normalized traffic density index
#mapview::mapview(traffic_buffers, zcol = "buffer_100m_normalized")

# Save the normalized traffic density index
saveRDS(traffic_buffers, file.path(wdir2, "traffic_buffers_norm_def.RDS"))
