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


# 1. F_ClipToRealisedRange: function which clips the current distribution range to the realised distribution range 
# 2. F_MaskLandUse:         function which uses a land use map to masks unsuitable habitat from the distribution maps

# 1. function which clips the current distribution range to the realised distribution range 
F_ClipToRealisedRange <- function(RespName,ClipToRealisedRange,DispersalAssumption,Scenario,Species_RangeMap){
  if(ClipToRealisedRange == TRUE & Scenario == "current"){
    # load shapefile with realised species range map
    r_Realised_SpeciesRange <- rast(file.path(user_dir, base_dir, Realised_SpeciesRanges,paste0("range_", RespName,".tif")))
    # change values in the SDM range outside of the POWO range to value = 0
    try( 
      Species_RangeMap <- mask(Species_RangeMap, r_Realised_SpeciesRange, maskvalues = 0, updatevalue = 0))
    rm("r_Realised_SpeciesRange")
    gc()
    return(Species_RangeMap )
    
  } else {
    return(Species_RangeMap )
  }
}

# 2. function which uses a land use map to masks unsuitable habitat from the distribution maps
F_MaskLandUse <- function(LUMask, Species_RangeMap){
  if(LUMask == TRUE){
    crs(Species_RangeMap) <- "EPSG:3035"
    LandUse_mask <- rast(file.path(user_dir,base_dir, LU_map))
    Species_RangeMap <- mask(Species_RangeMap, LandUse_mask)
    return(Species_RangeMap)
  } else {
    return(Species_RangeMap)
  }
}




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

