setwd("/home/mauro/Documenti/MODEL_EVAL/SCENARIO/ESM2_rcp2p6/")

# Load required libraries
library(ggplot2)

# Function to read data from ASCII file
read_data <- function(file_path) {
  # Read data from file
  data <- as.matrix(read.table(file_path))
  return(data)
}

# Function to create boxplot
create_boxplot <- function(data, color) {
  # Create boxplot
  p <- ggplot(data.frame(y = "gpp_10y_avg"), aes(x = "interval_year", y = "gpp_10y_avg")) +
    geom_boxplot(fill = color) +
    theme_minimal() +
    labs(x = NULL, y = NULL) +
    coord_flip() +
    theme(legend.position = "none")
  return(p)
}

# Function to create xy plot
create_xyplot <- function(data, color) {
  # Create xy plot
  p <- ggplot(data.frame(data), aes(x = "interval_year", y = "gpp_10y_avg")) +
    geom_point(color = color, alpha = 0.5) +
    theme_minimal() +
    labs(x = NULL, y = NULL) +
    theme(legend.position = "none")
  return(p)
}

# Loop to create plots
sites <- c("Collelongo", "Bily_Kriz")
for (i in sites) {
  # Read data from ASCII files
  file1 <- paste0("3D-CMCC-FEM-v.5.6_", i,"_ESM2_rcp2p6_boxplot")
  file2 <- paste0("3D-CMCC-FEM-v.5.6_",i,"_ESM2_rcp2p6_plot_gpp")
  # data1 <- read_data(file1)
  # data2 <- read_data(file2)
  data1 <- read.table(file1, 
                     header = TRUE,          # If your file has a header
                     sep = ",",              # Specify the delimiter (tab, comma, etc.)
                     fill = TRUE,            # Fill missing columns with NA
                     na.strings = "NA"       # Define the representation of missing values
  )
  data2 <- read.table(file2, 
                     header = TRUE,          # If your file has a header
                     sep = ",",              # Specify the delimiter (tab, comma, etc.)
                     fill = TRUE,            # Fill missing columns with NA
                     na.strings = "NA"       # Define the representation of missing values
  )
  
  # View the structure of the data
  str(data)
  # View the first few rows of the data
  head(data)
  
  # Define colors
  colors <- c("green", "yellow", "red")
  
  # Create boxplot and xy plot
  boxplot <- create_boxplot(data1, colors[i])
  xyplot <- create_xyplot(data2, colors[i])
  
  # Combine plots
  combined_plot <- gridExtra::grid.arrange(boxplot, xyplot, ncol = 2)
  
  # Print combined plot
  print(combined_plot)
}

# Add legend at bottom left
legend_plot <- ggplot() +
  geom_blank() +
  theme_void() +
  scale_fill_manual(values = colors, name = "Legend", labels = c("Plot 1", "Plot 2", "Plot 3"))

# Print legend plot
print(legend_plot)

