############### ###############
## sumstats.R
## Project: CBO
## Author: Kamil Kouhen
## Purpose: reporting significant changes made to the datasets in excel file format
## Date of creation: 01/05/2022
############### ###############

# Purpose: reporting significant changes made to the datasets in excel file format
# Output printed in Output > Cleaning

reporting.changes <- function(df, selected.variable = "", describe = ""){
  if (!("tidyverse" %in% .packages()) | !("readxl" %in% .packages()) | !("writexl" %in% .packages()) | !("here" %in% .packages())){
    stop("tidyverse, readxl and writexl are needed for this function, please load them before using this function")
    break
  } else{

    dataname <- deparse(substitute(df))
    variablename <- as.character(selected.variable)

    date <- str_replace(str_replace(str_replace(str_replace(paste0(Sys.time()), "-", ""), ":", ""), "-", ""), ":", "")

    arg <- match.call() #Making sure variables get recognized

    if (!(file.exists(paste0(here("Output", "Cleaning", "Changes made to datasets.xlsx"))))){ ##If the function has already been ran, the excel file should already be in here("Output", "For Cleaning")
      assign(paste0("Changes"), tibble( #Creating dataset that records all the flagged data
        data = character(),
        variable = character(),
        description = character(),
        last.update = character()
      ))
    } else{
      Changes <- readxl::read_excel(here("Output", "Cleaning", "Changes made to datasets.xlsx"))
    }

    #Command to add the flag to Changes
    Changes <- Changes %>%
      dplyr::mutate(#Making sure variable classes are ok after import from excel
        data = as.character(data),
        variable = as.character(variable),
        description = as.character(description),
        last.update = as.character(last.update)
      ) %>%
      add_row(
        data = dataname,
        variable = variablename,
        description = as.character(describe),
        last.update = as.character(paste0(Sys.time()))
      ) %>% #Avoiding duplicates
      distinct(data, variable, description, .keep_all = TRUE)

    #exporting to output in excel format
    write_xlsx(Changes, here("Output", "For Cleaning", "Changes made to datasets.xlsx"))
  }
}
