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


### Functions for post-processing the SDM-predictions
# 1. F_PostProcessingSDMs:  function which applies all clips to the distribution ranges, using the other functions

F_PostProcessingSDMs <- function(RespName, 
                       Scenarios,
                       ClipToRealisedRange,
                       SetValuesUnderThresholdToZero,
                       SetValuesAboveThresholdToOne,
                       DispersalAssumption){
  
  
  
    dt_Rangesizes <- data.table(RespName)
    
    tryCatch({  
    for(Scenario in Scenarios){
      
      write(paste0("Start: ", RespName, " & scenario: ", Scenario),
            file.path(user_dir,base_dir,species_out_dir,LogFile),append=TRUE)
      
      #	1. load SDM-range maps
      Species_RangeMap <- rast(file.path(user_dir, base_dir, SDM_predictions,Scenario,paste0(RespName,".tif")))
      
      #	2. clip current range maps to POWO-ranges 
      Species_RangeMap <- F_ClipToRealisedRange(RespName = RespName,
                                                ClipToRealisedRange = ClipToRealisedRange,
                                                Scenario = Scenario,
                                                Species_RangeMap = Species_RangeMap)
      
      # 3. clip range map to land use barrier map
      Species_RangeMap <- F_MaskLandUse(LUMask = LUMask,
                                        Species_RangeMap = Species_RangeMap )
    
        
      # 4. binarize the PoOs
      Species_RangeMap <- F_binarize_PoOs(SetValuesUnderThresholdToZero = SetValuesUnderThresholdToZero, 
                                          SetValuesAboveThresholdToOne = SetValuesAboveThresholdToOne,
                                          DispersalAssumption = DispersalAssumption,
                                          Scenario = Scenario,
                                          RespName = RespName, 
                                          Species_RangeMap = Species_RangeMap)
      
      # 5: apply dispersal assumption to scenario range maps 
      Species_RangeMap <- F_DispersalAssumption(DispersalAssumption = DispersalAssumption,
                                                Scenario = Scenario,
                                                RespName = RespName,
                                                Species_RangeMap = Species_RangeMap)
        
      #	6. save the clipped  and binarized rasters to the hard disk
      writeRaster(Species_RangeMap, 
                  file.path(user_dir,base_dir,species_out_dir,"RangeMaps", Scenario,paste0(RespName,".tif")), overwrite=TRUE)

      # calculate range size
      # for species with no suitable range within the study extent
      maxMapValue <- max(na.omit(values(Species_RangeMap)))
      if(maxMapValue == 0){
        RangeSize <- 0
      }
      # for binarized rasters (values of raster are either 0 or 1)
      if(maxMapValue == 1){
        RangeSize <- sum(na.omit(values(Species_RangeMap)))  
      } 
      # for rasters that include probability values that range between 0 and 1000
      if(maxMapValue > 1){
        RangeSize <- sum(na.omit(values(Species_RangeMap)))/1000  
      }
      
        
      # and append it to the table
      colnames <- names(dt_Rangesizes)
      dt_Rangesizes <- cbind(dt_Rangesizes, RangeSize)
      names(dt_Rangesizes) <- c(colnames,Scenario)
      
      rm("Species_RangeMap")
      gc()
      

    }
    return(dt_Rangesizes )

}, error = function(e){
  setwd(file.path(user_dir,base_dir))
  write(paste0("ERROR: ", RespName, " aborted!"),
        file.path(user_dir,base_dir,species_out_dir,LogFile),append=TRUE)
  
  dt_Rangesizes <- as.data.table(matrix(c(RespName,rep(NA, length(Scenarios))), nrow = 1, ncol = length(Scenarios) + 1))
  names(dt_Rangesizes) <- c("RespName",Scenarios)
  return(dt_Rangesizes )
  
})
  

}




# ====================================================================
#
# 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.
#
# 
# ====================================================================

