###################  inici grafiques Surenexus  ################################

paquets <- c("xml2", "htmltools", "ggthemes", "paletteer", "htmlwidgets", "plotly", "dplyr")

# Comprova si els paquets estan instal·lats
installp <- paquets %in% rownames(installed.packages())

# Instal·la els que no ho estiguin des del CRAN per defecte
if (any(!installp)) {
  install.packages(paquets[!installp], repos = "https://cloud.r-project.org")
}


# Carrega els paquets
lapply(paquets, library, character.only = TRUE)

###################################################################################################################################################
###################################################################################################################################################
###################################################################################################################################################

#########################################################  inici grafiques Surenexus  #############################################################

###################################################################################################################################################
###################################################################################################################################################
###################################################################################################################################################


# qttEnergyWaterTreatment
# qttTreatedWater
# qualityInletCOD
# qualityOutletCOD
# qualityInletN
# qualityOutletN

sumfun<-function(x,start,end){
  return(sum(x[start:end]))
}

report="qttEnergyUsed"

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]

stages<-c()
for(stage in experiments) {
  stages<-c(stages,rep(stage,12))
}


dataframe <-data.frame(time, report_stage, values)

Energy<-c()
i<-1
for (stage in experiments) {
  
  report_by_stage<-dataframe[dataframe$report_stage==stage,]
  for (j in c(0:11)) {
    Energy[(i-1)*12+(j+1)]<-sumfun(report_by_stage$values,(j)*30+1,((j+1)*30))
  }
  i=i+1
}


report="qttLiquidWaste"

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]


dataframe <-data.frame(time, report_stage, values)

TreatedWater<-c()
i<-1
for (stage in experiments) {
  
  report_by_stage<-dataframe[dataframe$report_stage==stage,]
  j<-1
  TreatedWater[(i-1)*12+(j)]<-sum(report_by_stage$values[(j*c(1:30))])
  for (j in c(2:12)) {
    TreatedWater[(i-1)*12+(j)]<-sum(report_by_stage$values[(j*c(1:30))])
  }
  
  #TreatedWater[i]<-sum(report_by_stage$values)
  i=i+1
}



report="qualityInletCOD"

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]

#Passem de mg/l a kg/ha/dia 
values<-values*0.1

dataframe <-data.frame(time, report_stage, values)

qualityInletCOD<-c()
aux<-c()
i<-1
for (stage in experiments) {
  
  report_by_stage<-dataframe[dataframe$report_stage==stage,]
  
  for (j in c(1:12)) {
    qualityInletCOD[(i-1)*12+(j)]<-sumfun(report_by_stage$values,(j-1)*30,(j*30))
  }
  
  i=i+1
}


report="qualityOutletCOD"

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]


#Passem de mg/l a kg/ha/dia 
values<-values*0.1

dataframe <-data.frame(time, report_stage, values)

qualityOutletCOD<-c()
i<-1
for (stage in experiments) {
  
  report_by_stage<-dataframe[dataframe$report_stage==stage,]
  
  for (j in c(1:12)) {
    qualityOutletCOD[(i-1)*12+(j)]<-sumfun(report_by_stage$values,(j-1)*30,(j*30))
  }
  
  i=i+1
}

removedCOD<-qualityInletCOD-qualityOutletCOD
dataframe <- data.frame(Energy,TreatedWater,removedCOD,stages)

fig <- plot_ly(dataframe, x = ~Energy, y = ~TreatedWater, z = ~removedCOD, color=~stages, colors=c("#C7EBB1","#5CC0C0","#699AC2","#2A5783"))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Energy Consumption (kw)'),
                                   yaxis = list(title = 'Treated Water (m3)'),
                                   zaxis = list(title = 'Removal COD (kg/ha/mes)')))

fig

htmlwidgets::saveWidget(as_widget(fig), "1-NexusCOD.html",selfcontained = FALSE, libdir = "common_libs")



report="qualityInletN"

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]


#Passem de mg/l a kg/ha/dia 
values<-values*0.1

dataframe <-data.frame(time, report_stage, values)

qualityInletN<-c()
i<-1
for (stage in experiments) {
  
  report_by_stage<-dataframe[dataframe$report_stage==stage,]
  
  for (j in c(1:12)) {
    qualityInletN[(i-1)*12+(j)]<-sumfun(report_by_stage$values,(j-1)*30,(j*30))
  }
  
  i=i+1
}


report="qualityOutletN"

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]


#Passem de mg/l a kg/ha/dia 
values<-values*0.1

dataframe <-data.frame(time, report_stage, values)

qualityOutletN<-c()
i<-1
for (stage in experiments) {
  
  report_by_stage<-dataframe[dataframe$report_stage==stage,]
  
  for (j in c(1:12)) {
    qualityOutletN[(i-1)*12+(j)]<-sumfun(report_by_stage$values,(j-1)*30,(j*30))
  }
  
  i=i+1
}

removedN <-qualityInletN-qualityOutletN

dataframe <- data.frame(Energy,TreatedWater,removedN,stages)
colorsList<-paletteer_c("ggthemes::Green-Blue Diverging", 30)[1:length(stages)]
colorsList<-colorsList[1:4]

fig <- plot_ly(dataframe, x = ~Energy, y = ~TreatedWater, z = ~removedN, color=~stages, colors=c("#C7EBB1","#5CC0C0","#699AC2","#2A5783"))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'X Axis : Energy Consumption (kw)'),
                                   yaxis = list(title = 'Y Axis : Treated Water (m3)'),
                                   zaxis = list(title = 'Z Axis : Removal N (kg/ha/mes)')))

fig

htmlwidgets::saveWidget(as_widget(fig), "1-NexusN.html",selfcontained = FALSE, libdir = "common_libs")



dataframe <- data.frame(Energy,removedCOD,removedN,stages)
colorsList<-paletteer_c("ggthemes::Green-Blue Diverging", 30)[1:length(stages)]
colorsList<-colorsList[1:4]

fig <- plot_ly(dataframe, x = ~removedN, y = ~removedCOD, z = ~Energy, color=~stages, colors=c("#C7EBB1","#5CC0C0","#699AC2","#2A5783"))
fig <- fig %>% add_markers()
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Removal N (kg/ha/mes)'),
                                   yaxis = list(title = 'Removal COD (kg/ha/mes)'),
                                   zaxis = list(title = 'Energy Consumption (kw)')))

fig

htmlwidgets::saveWidget(as_widget(fig), "1-NVsCODVsEnergy.html",selfcontained = FALSE, libdir = "common_libs")



report="qttWaterRealNeeded"


stage=experiments[1]

values <-as.numeric(as.character(report_values$varvalue[report_values$varname == report]))
time <-as.numeric(as.character(report_values$xTime[report_values$varname == report]))
report_stage <-report_values$label[report_values$varname == report]

dataframe <-data.frame(time, report_stage, values)

report_by_stage<-dataframe[dataframe$report_stage==stage,]

water<-report_by_stage$values[1:360]

water[water < 0] <- 0
acc_water<-c()
i=1
for (i in c(1:12)) {
  acc_water[i]<-sum(water[((i-1)*30+1):(i*30)])
  i<-i+1
}


stage=experiments[2]

report_by_stage<-dataframe[dataframe$report_stage==stage,]

water<-report_by_stage$values[1:360]

water[water < 0] <- 0
acc_waterIrr<-c()
i=1
for (i in c(1:12)) {
  acc_waterIrr[i]<-sum(water[((i-1)*30+1):(i*30)])
  i<-i+1
}


x <- c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
y1 <- acc_water
y2 <- acc_waterIrr
z<-acc_water-acc_waterIrr
z<-cumsum(z)
data <- data.frame(x, y1, y2,z)

#The default order will be alphabetized unless specified as below:
data$x <- factor(data$x, levels = data[["x"]])

fig <- plot_ly(data, x = ~x, y = ~y1, type = 'bar', name = 'default.param1', marker = list(color = 'rgb(49,130,189)'))
fig <- fig %>% add_trace(y = ~y2, name = 'default.param2', marker = list(color = 'rgb(100,204,250)'))

fig <-  fig %>% add_trace(data , x = ~x, y = ~z, type = 'scatter',  mode = 'lines', name = 'water saved')
fig <- fig %>% layout(xaxis = list(title = "", tickangle = -45),
                      yaxis = list(title = "m3"),
                      margin = list(b = 100),
                      barmode = 'group', title = ("Water used"))

fig

htmlwidgets::saveWidget(as_widget(fig), "1-waterByIrrigationMonthly.html",selfcontained = FALSE, libdir = "common_libs")

num_exp <- 1
end <- TRUE
all_data <- list()

while (end) {
  folder <- paste0("s_", num_exp)
  directory <- file.path(folder, "data", "result.csv")
  end <- file.exists(directory)
  
  if (end) {
    results <- read.csv2(directory, header = TRUE, sep = ";", row.names = NULL, check.names = FALSE)
    if (nrow(results)!=0){
      results$num_exp <- num_exp
      # Convertim totes les columnes (excepte 'Version' i 'num_exp') a numèriques
      cols_to_convert <- setdiff(names(results), c("Version", "num_exp"))
      results[cols_to_convert] <- lapply(results[cols_to_convert], function(x) as.numeric(as.character(x)))
      
      all_data[[length(all_data) + 1]] <- results
    }
  }
  
  num_exp <- num_exp + 1
}

# Ara podem combinar sense errors
combined <- bind_rows(all_data)

# Tornem a calcular les columnes amb valors diferents de zero
cols_to_convert <- setdiff(names(combined), c("Version", "num_exp", "row.names"))
cols_no_zero <- cols_to_convert[colSums(combined[cols_to_convert], na.rm = TRUE) != 0]

# cols_no_zero <- gsub("Percent", "", cols_no_zero)											
# Crear una gràfica per cada columna amb valors
for (col in cols_no_zero) {
  grafica <- plot_ly()
  
  for (exp in unique(combined$num_exp)) {
    df_exp <- combined %>% filter(num_exp == exp)
    grafica <- grafica %>%
      add_trace(x = df_exp$row.names,
                y = df_exp[[col]],
                type = 'scatter',
                mode = 'lines',
                name = paste("default.param", exp))
  }
  col <- gsub("Percent", "", col)											
  grafica <- grafica %>%
    layout(title = paste("Evolution of", col, "by scenario"),
           xaxis = list(title = "Simulation time"),
           yaxis = list(title = col))
  
  # Desa la gràfica
  nom_fitxer <- paste0(col, "_comparativa_plotly.html")
  saveWidget(as_widget(grafica), nom_fitxer, selfcontained = FALSE, libdir = "common_libs")
}

###################################################################################################################################################
###################################################################################################################################################
###################################################################################################################################################

###################  inici grafiques Marene  ################################

###################################################################################################################################################
###################################################################################################################################################
###################################################################################################################################################





xml_file <- read_xml("experiment.exp")

# Extreu tots els experiments
experiments <- xml_find_all(xml_file, ".//experiment")
# Variables d'interès
vars <- c("%TC%", "%TS%", "%TRA%", "%INF%", "%TV%", "%TF%", "%VENT%", "%FS%", "%REF%")

# Inicialitza una llista per guardar les dades
data_list <- lapply(vars, function(v) character(0))
names(data_list) <- vars

# Extreu les dades de cada experiment
for (exp in experiments) {
  variables <- xml_find_all(exp, ".//variable")
  for (var in variables) {
    name <- xml_attr(var, "name")
    value <- xml_attr(var, "value")
    if (name %in% vars) {
      data_list[[name]] <- c(data_list[[name]], value)
    }
  }
}

# Filtra variables: només les que són numèriques i tenen més de 10 valors vàlids
data_list <- lapply(data_list, function(x) suppressWarnings(as.numeric(x)))


# Funció de transformació
transforma <- function(x) {
  1 / ((x / 0.034) + 0.3)
}

# Sobreescriure les variables amb els valors transformats
data_list$`%TF%` <- transforma(data_list$`%TF%`)
data_list$`%TC%` <- transforma(data_list$`%TC%`)

data_list <- Filter(function(x) !all(is.na(x)) && length(na.omit(x)) > 5, data_list)

# Converteix a data frame
df <- as.data.frame(data_list)

if (!nrow(df) == 0 && ncol(df) == 0) {

# Crea els gràfics amb Plotly
plots <- lapply(names(data_list), function(var) {
  plot_ly(x = data_list[[var]], type = "histogram", nbinsx = 10) %>%
    layout(title = paste(var, " Histogram"),
           xaxis = list(title = var),
           yaxis = list(title = "Frequency"))
})

# Combina els gràfics en una pàgina HTML
html_page <- tagList(
  tags$html(
    tags$head(tags$title("Histogrames de Variables")),
    tags$body(
      lapply(plots, function(p) {
        tagList(
          as.tags(p),
          tags$br(), tags$br(), # dos salts de línia
          tags$hr(), # línia horitzontal
          tags$br()
        )
      }))
    
  )
)



save_html(html_page, "1-Variables_Experiment_Histogram.html")

}

###############################################################################

f <- list(
  family = "Courier New, monospace",
  size = 18,
  color = "#7f7f7f")
units <- "[kWh]"

#Heating VS Cooling Grafica

Area <- report_values[report_values$varname == "Building_Area_EP",]$varvalue

Heating <- report_values[report_values$varname == "District_Heating_Heating",]$varvalue
Cooling <- report_values[report_values$varname == "District_Cooling_Cooling",]$varvalue
values_label<- report_values[report_values$varname == "District_Heating_Heating",]$label

aux <- rep.int("s", length(values_label))
vis<-c(1:length(values_label))
values_label<-paste(aux, vis, sep="_")

Heating <- as.numeric(as.character(Heating))
Cooling <- as.numeric(as.character(Cooling))

graficFile <- paste("Heating-Cooling-",nameFile,sep="")

x <- list(
  title = paste("Heating ",units),
  titlefont = f
)
y <- list(
  title = paste("Cooling ",units),
  titlefont = f
)

library(plotly)
grafica1 <- plot_ly(
  x = Heating,
  y = Cooling,
  text = values_label,
  name = "HeatingCooling",
  mode = "markers",
  type = "scatter"
) %>%
  layout(xaxis = x, yaxis = y)

#(gg <- ggplotly(p))

grafica <- paste("1-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(grafica1), grafica,selfcontained = FALSE, libdir = "common_libs")

######################################### Histograms ######################################### 

library(plotly)
library(htmlwidgets)

# Extracció de valors
Heating <- as.numeric(as.character(report_values$varvalue[report_values$varname == "District_Heating_Heating"]))
Cooling <- as.numeric(as.character(report_values$varvalue[report_values$varname == "District_Cooling_Cooling"]))

# Histograma de Heating
fig_heating <- plot_ly(
  x = Heating,
  type = "histogram",
  name = "Heating",
  marker = list(color = "red"),
  opacity = 0.75
) %>%
  layout(
    title = "Histogram of Heating",
    xaxis = list(title = "Heating Values"),
    yaxis = list(title = "Frequency")
  )

# Guardar com a HTML
saveWidget(as_widget(fig_heating), "1-Heating_Histogram.html", selfcontained = FALSE, libdir = "common_libs")

# Histograma de Cooling
fig_cooling <- plot_ly(
  x = Cooling,
  type = "histogram",
  name = "Cooling",
  marker = list(color = "blue"),
  opacity = 0.75
) %>%
  layout(
    title = "Histogram of Cooling",
    xaxis = list(title = "Cooling Values"),
    yaxis = list(title = "Frequency")
  )

# Guardar com a HTML
saveWidget(as_widget(fig_cooling), "1-Cooling_Histogram.html", selfcontained = FALSE, libdir = "common_libs")


####################################################################


lineV<-rep("HC",length(Heating))
HC <-data.frame(Heating,Cooling,values_label,lineV)


p <- ggplot(data = HC, aes(x = Heating, y = Cooling)) +
  geom_point(aes(text = paste("Stage:", values_label)), size = 1) +
  geom_smooth(aes(colour = lineV, fill = lineV)) +
  facet_wrap(~ lineV) +
  labs(
    x = paste("Heating", units),
    y = paste("Cooling", units),
    title = "Heating-Cooling-Line"
  ) +
  
  theme(
    plot.title = element_text(
      family = "Courier New",
      size = 18,
      colour = "#7f7f7f"
    )
  )

gg <- ggplotly(p)

graficFile <- paste("Heating-Cooling-Line-",nameFile,sep="")

grafica <- paste("1-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(gg), grafica,selfcontained = FALSE, libdir = "common_libs")

####################################################################


# Electricity_Interior_Equipment Grafica

Interior <- report_values[report_values$varname == "Electricity_Interior_Equipment",]$varvalue
#Inter <- report_values[report_values$varname == "Electricity_Interior_Equipment",]$label

Interior <- as.numeric(as.character(Interior))
#Cooling <- as.numeric(as.character(Cooling))

graficFile <- paste("Electricity_Interior_Equipment-",nameFile,sep="")

x <- list(
  title = "Stage",
  titlefont = f
)
y <- list(
  title = paste("Interior Equipment ",units),
  titlefont = f
)

library(plotly)
grafica1 <- plot_ly(
  x = values_label,
  y = Interior,
  text = values_label,	
  name = "Interior-Equipment",
  mode = "markers"
) %>%
  layout(xaxis = x, yaxis = y)

grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(grafica1), grafica,selfcontained = FALSE, libdir = "common_libs")

# Electricity_Interior_Lighting Grafica

Interior <- report_values[report_values$varname == "Electricity_Interior_Lighting",]$varvalue
#Inter <- report_values[report_values$varname == "Electricity_Interior_Equipment",]$label

Interior <- as.numeric(as.character(Interior))
#Cooling <- as.numeric(as.character(Cooling))

graficFile <- paste("Electricity_Interior_Lighting-",nameFile,sep="")

x <- list(
  title = "Stage",
  titlefont = f
)
y <- list(
  title = paste("Interior Lightning ",units),
  titlefont = f
)

library(plotly)
grafica1 <- plot_ly(
  x = values_label,
  y = Interior,
  text = values_label,
  name = "Interior-Lightning",
  mode = "markers"
)%>%
  layout(xaxis = x, yaxis = y)

grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(grafica1), grafica,selfcontained = FALSE, libdir = "common_libs")

# District_Heating_Water_Systems Grafica

Interior <- report_values[report_values$varname == "District_Heating_Water_Systems",]$varvalue

Interior <- as.numeric(as.character(Interior))

graficFile <- paste("District_Heating_Water_Systems-",nameFile,sep="")

y <- list(
  title = "District Heating Water Systems [m3]",
  titlefont = f
)
x <- list(
  title = "Stage",
  titlefont = f
)

library(plotly)
grafica1 <- plot_ly(
  x = values_label,
  y = Interior,
  text = values_label,
  name = "Water-Systems-Heating",
  mode = "markers",
  type = "scatter"
)%>%
  layout(xaxis = x, yaxis = y)

grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(grafica1), grafica,selfcontained = FALSE, libdir = "common_libs")




label<-c()

num_exp<-1
end <- TRUE

while(end) { 
  folder <- paste("s_",as.character(num_exp),sep="")
  directory <- paste(folder,"\\data\\variables.csv",sep="")
  end <- file.exists(directory)
  if (end) {
    label[num_exp] <- folder
  }
  num_exp <- num_exp+1
}

global_warming_potential<-c()
renewable_primary_energy_use_by_nonrenewable<-c()
hazardous_and_nonhazardous_for_final_disposal<-c()
surfaces<-c()
construction<-c()

num_exp<-1
end <- TRUE

while(end) { 
  folder <- paste("s_",as.character(num_exp),sep="")
  directory <- paste(folder,"\\data\\solutions-r.csv",sep="")
  end <- file.exists(directory)
  directory <- paste(folder,"\\data\\materials-r.csv",sep="")
  end <- end && file.exists(directory)
  directory <- paste(folder,"\\data\\variables.csv",sep="")
  end <- end && file.exists(directory)
  if (end) {
    materials <- read.csv2(paste(folder,"\\data\\materials-r.csv",sep=""), header = TRUE, sep = ";")
    solutions <- read.csv2(paste(folder,"\\data\\solutions-r.csv",sep=""), header = TRUE, sep = ";")
    variables <- read.csv2(paste(folder,"\\data\\variables.csv",sep=""), header = TRUE, sep = ";")
    solutions[is.na(solutions)]<-c(0)
    materials[is.na(materials)]<-c(0)
    
    if (("surface" %in% colnames(variables))) surfaces[num_exp] <- c(variables["surface"])
    else surfaces[num_exp] <- as.numeric(as.character(Area[num_exp]))
    
    construction[num_exp]<-c(as.numeric(as.character(materials[materials$titles==c("total"),"construction"])) + as.numeric(as.character(solutions[solutions$titles==c("total"),"construction"])))
    global_warming_potential[num_exp]<-c(as.numeric(as.character(materials[materials$titles==c("total"),"global_warming_potential"])))
    renewable_primary_energy_use_by_nonrenewable[num_exp]<-c(as.numeric(as.character(materials[materials$titles==c("total"),"renewable_primary_energy_use_by_nonrenewable"])))
    hazardous_and_nonhazardous_for_final_disposal[num_exp]<-c(as.numeric(as.character(materials[materials$titles==c("total"),"hazardous_and_nonhazardous_for_final_disposal"])))
  }
  num_exp <- num_exp+1
}

y <- list(
  title = " "
)

p <- plot_ly(
  x = label,
  y = construction,
  name = "Construction",
  type = "bar",
  filename="r-docs/simple-bar"
) %>% layout(yaxis = y)

p2 <- add_trace(
  p,
  x = label,
  y = global_warming_potential,
  name = "Global warming potential",
  type = "bar",
  filename="r-docs/simple-bars"
)

p3 <- add_trace(
  p2,
  x = label,
  y = hazardous_and_nonhazardous_for_final_disposal,
  name = "Hazardous and nonhazardous for final disposal",
  type = "bar",
  filename="r-docs/simple-bars"
)

p4 <- add_trace(
  p3,
  x = label,
  y = renewable_primary_energy_use_by_nonrenewable,
  name = "Renewable primary energy use by nonrenewable",
  type = "bar",
  filename="r-docs/simple-bars"
)

#layout(p4, barmode = "stack")

graficFile <- paste("Indicators-",nameFile,sep="")

grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(layout(p4, barmode = "stack")), grafica,selfcontained = FALSE, libdir = "common_libs")

#Grafica en surface

p <- plot_ly(
  x = label,
  y = as.numeric(construction)/as.numeric(surfaces),
  name = "Euros Construction/m2",
  type = "bar",
  filename="r-docs/simple-bar"
) %>% layout(yaxis = y)

p2 <- add_trace(
  p,
  x = label,
  y = as.numeric(global_warming_potential)/as.numeric(surfaces),
  name = "Global warming potential/m2",
  type = "bar",
  filename="r-docs/simple-bars"
)

p3 <- add_trace(
  p2,
  x = label,
  y = as.numeric(hazardous_and_nonhazardous_for_final_disposal)/as.numeric(surfaces),
  name = "Hazardous and nonhazardous for final disposal/m2",
  type = "bar",
  filename="r-docs/simple-bars"
)

p4 <- add_trace(
  p3,
  x = label,
  y = as.numeric(renewable_primary_energy_use_by_nonrenewable)/as.numeric(surfaces),
  name = "Renewable primary energy use by nonrenewable/m2",
  type = "bar",
  filename="r-docs/simple-bars"
)

#layout(p4, barmode = "stack")

graficFile <- paste("Indicators-m2-",nameFile,sep="")

grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(layout(p4, barmode = "stack")), grafica,selfcontained = FALSE, libdir = "common_libs")

#Càlcul de la gràfica 3d

total_demand_30_years <- (as.numeric(renewable_primary_energy_use_by_nonrenewable)/as.numeric(surfaces))*0.2777778

#Passem a 30 anys
Heating_Cooling <- ((Heating+Cooling)*30)/as.numeric(surfaces)
total_demand_30_years <- total_demand_30_years+Heating_Cooling

# Passem a KWH per a fer els càlculs de CO2 i €
euros_Heating_Cooling <- total_demand_30_years*0.139141
CO2_Heating_Cooling <- total_demand_30_years*0.357
euros_materials <- as.numeric(construction)/as.numeric(surfaces)

total_euros <- euros_materials + euros_Heating_Cooling

CO2_materials <- as.numeric(global_warming_potential)/as.numeric(surfaces)
total_CO2 <- CO2_materials + CO2_Heating_Cooling

#gràfica 3d save file
p<-plot_ly(x = total_demand_30_years, y = total_euros, z = total_CO2, type="scatter3d", mode="lines+markers", text=paste("Stage : ",label), color=total_demand_30_years)

graficFile <- paste("3Dv1-",nameFile,sep="")

grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(layout(p)), grafica,selfcontained = FALSE, libdir = "common_libs")


p <- plot_ly(
  x = label,
  y = as.numeric(construction)/as.numeric(surfaces),
  name = "Euros Construction/m2",
  type = "bar",
  filename="r-docs/simple-bar"
) 

p2 <- add_trace(
  p,
  x = label,
  y = as.numeric(global_warming_potential)/as.numeric(surfaces),
  name = "Global warming potential/m2",
  type = "bar",
  filename="r-docs/simple-bars"
)

p3 <- add_trace(
  p2,
  x = label,
  y = as.numeric(hazardous_and_nonhazardous_for_final_disposal)/as.numeric(surfaces),
  name = "Hazardous and nonhazardous for final disposal/m2",
  type = "bar",
  filename="r-docs/simple-bars"
)

p4 <- add_trace(
  p3,
  x = label,
  y = as.numeric(renewable_primary_energy_use_by_nonrenewable)/as.numeric(surfaces),
  name = "Renewable primary energy use by nonrenewable/m2",
  type = "bar",
  filename="r-docs/simple-bars"
)


p5 <- add_trace(
  p4,
  x = label,
  y = total_euros,
  name = "Euros/m2",
  type = "lines",
  filename="r-docs/simple-bars"
)

p6 <- add_trace(
  p5,
  x = label,
  y = total_demand_30_years,
  name = "kWh/m2 30 years",
  type = "lines",
  filename="r-docs/simple-bars"
)

p7 <- add_trace(
  p6,
  x = label,
  y = total_CO2,
  name = "CO2/m2",
  type = "lines",
  filename="r-docs/simple-bars"
)

graficFile <- paste("Complete-Bars-",nameFile,sep="")


grafica <- paste("plotly-",graficFile,sep="")
grafica <- paste(grafica,".html",sep="")

htmlwidgets::saveWidget(as_widget(p7), grafica,selfcontained = FALSE, libdir = "common_libs")

