#' Save output
#'
#' This function saves data frames and plots generated by EpiCompare.
#'
#' @param save_output Default FALSE. If TRUE, outputs are saved.
#' @param file Tables and plots to be saved.
#' @param file_type Type of file to be saved.
#' "data.frame", "ggplot", "image"
#' @param filename Name of file.
#' @param outpath Outpath
#' @param interactive Default FALSE. If TRUE, interactive plots are saved as
#' html.
#' @param verbose Print messages.
#'
#' @importFrom htmltools save_html
#' @importFrom data.table fwrite
#' @importFrom ggplot2 ggsave
#'
#' @return Saved data frames and plots.
#' @keywords internal 
save_output <- function(save_output = FALSE,
                        file,
                        file_type,
                        filename,
                        outpath,
                        interactive = FALSE,
                        verbose = TRUE){

  if(isTRUE(save_output)){
    dir.create(outpath, showWarnings = FALSE, recursive = TRUE)
    if(file_type == "data.frame"){
      messager("Saving CSV file ==>",file,v=verbose)
      data.table::fwrite(x = file,
                         file = file.path(
                           outpath,
                           paste0(gsub("\\.txt|\\.csv","",basename(filename)),
                                  ".csv")),
                         sep = "\t")
    }else if(file_type == "ggplot"){ 
      ## Save interactive HTML
      if(isTRUE(interactive)){
        messager("Saving HTML  ==>",file,v=verbose)
        htmltools::save_html(html = file,
                             file = file.path(
                               outpath,paste0(basename(filename),".html")
                               )
                             )
      ## Save static PNG
      } else{
        messager("Saving PNG file ==>",file,v=verbose) 
        ggplot2::ggsave(filename = file.path(outpath,
                                             paste0(basename(filename),".png")
                                             ),
                        plot = file,
                        device = "png",
                        path = outpath)
        # unlink(paste0(filename,".png"))
      }
    }else if(file_type == "image"){
      messager("Saving PNG file ==>",file,v=verbose)
      check_dep("grDevices")
      grDevices::png(file.path(outpath, paste0(basename(filename),".png")))
      file
      grDevices::dev.off()
    }
  }
}
