# ====================================================================
#
# Copyright 2025, PBL Netherlands Environmental Assessment Agency
# See the copyright notice at the end of this file.
#
# ====================================================================


#14. SAVE ALL METRICS FILE 

## Write the metrics output for all species to a single file
SaveAllMetrics <- function(AllMetricsSave,Removeoriginal, RespNames){
  
  if(AllMetricsSave == TRUE){

    setwd(modelsetup$SpeciesMetrics.dir)
    
    metric_files <- list.files(pattern = "\\.csv$")
    metric_files <- metric_files[grep("metrics", metric_files)]
    
    Allmetrics <- rbindlist(lapply(metric_files,fread))
    Allmetrics <- Allmetrics[,-1]
    setnames(Allmetrics, make.names(names(Allmetrics)))
    
   
    fwrite(Allmetrics,file=("AllMetrics.csv"),row.names = FALSE)    
    
    # list species which do not have a valid SDM
    SpeciesWithErrors <- Allmetrics[is.na(MCC.GLM.cv), Species] 
    
    WriteLogFile(paste(user_dir, base_dir, species_out_dir, LogFile,sep="/"),
                 ln=paste0("Species without an SDM:", SpeciesWithErrors))
    
    if(Removeoriginal == TRUE){
    file.remove(c(metric_files))
    }
  } 
  
}





# ====================================================================
#
# Copyright 2025, PBL Netherlands Environmental Assessment Agency
# 
# This source code of the BioScore model is owned by PBL Netherlands Environmental Assessment Agency. 
# It is not permitted to copy, redistribute, remix, transform, and build upon the material without written approval of PBL. 
# Permission for commercial purposes will not be granted. 
# This code is published to improve the transparency of the models used by PBL, 
# but without any warranty for fitness for any other purpose. 
# After approval of PBL to use the code, PBL will not provide any support.
#
# 
# ====================================================================

