gc()

# installing packages for the environment
# (do it only once the first time you run this code)
install.packages('renv')
renv::restore()


set.seed(421)


library(rmarkdown)
library(knitr)
library(ggwordcloud)
library(dplyr)
library(RColorBrewer)
library(wordcloud)
library(wordcloud2)
library(htmlwidgets)
library(textplot)
library(quanteda.textplots)
library(webshot2)
library(chromote)


# Get a list of all CSV files in the CSV folder
csv_files <- list.files(path = "CSV", pattern = "\\.csv$", full.names = TRUE)

for (file_name in csv_files) {
  # Read the CSV file
  data <- read.csv(file_name)
  
  # Order the data by weight in descending order
  set.seed(421)
  data <- data[order(data$word, decreasing = TRUE), ]
  data <- data[order(data$weight, decreasing = TRUE), ]
  
  #Get colors from the dataset
  colors = subset(data, select = c(color))
  data = subset(data, select = -c(color) )
  data <- data %>% relocate(word)
  
  
  color_palette <- colors$color
  
  wordcloud <- wordcloud2(data, color = color_palette, size=1.3, 
                          backgroundColor = "white", shape = "circle", minRotation = 0, maxRotation = 0,
                          rotateRatio = 0, fontFamily = "Arial", shuffle = FALSE ) #, widgetsize =c("1500","1500")
  
  # Extract the file name without extension
  file_name_without_extension <- tools::file_path_sans_ext(basename(file_name))
  
  # Save the rendered widget as an HTML file
  saveWidget(wordcloud, "HTML/1.html", selfcontained = FALSE)
  
  webshot2::webshot("HTML/1.html",
                    paste0("", file_name_without_extension, ".png"),
                    delay = 2, zoom = 1, vwidth = 1447, vheight = 780)
}

