## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
eval_chunks <-
  CopernicusDataspace::dse_has_client_info() &&
  CopernicusDataspace::dse_has_account() &&
  CopernicusDataspace::dse_has_s3_secret()

## ----sh-collections, message=FALSE, eval=eval_chunks--------------------------
library(CopernicusDataspace)
library(stars) ## required below for reading and plotting data
library(dplyr) ## used for data manipulation below
dse_sh_collections()

## ----sh-search, eval=eval_chunks----------------------------------------------
bounds <- c(5.261, 52.680, 5.319, 52.715)
if (dse_has_client_info()) {
  dse_sh_search_request(
    collection = "sentinel-2-l2a",
    bbox       = bounds,
    datetime   = c("2025-01-01 UTC", "2025-01-31 UTC")
  ) |>
    filter(`eo:cloud_cover` <= 10) |>
    collect()
}

## ----prepare-sentinelhub, eval=eval_chunks------------------------------------
## prepare input data:
input <-
  dse_sh_prepare_input(
    bounds = bounds,
    time_range = c("2025-06-01 UTC", "2025-07-01 UTC")
  )

## prepare ouput format:
output <- dse_sh_prepare_output(bbox = bounds)

## retrieve processing script:
evalscript <- dse_sh_get_custom_script("/sentinel-2/l2a_optimized/")

## destination file:
fl <- tempfile(fileext = ".tiff")

## ----download-sentinelhub, eval=FALSE-----------------------------------------
# if (dse_has_client_info()) {
#   ## send request and download result:
#   dse_sh_process(input, output, evalscript, fl)
# }

## ----eval-scripts, eval=eval_chunks-------------------------------------------
dse_sh_custom_scripts()

## ----water-bodies, eval=eval_chunks-------------------------------------------

if (dse_has_client_info()) {
  evalscript <-
    dse_sh_get_custom_script("/sentinel-2/simple_water_bodies_mapping-swbm/")
  
  ## destination file:
  fl_waterbody <- tempfile(fileext = ".tiff")
  
  ## send request and download result:
  dse_sh_process(input, output, evalscript, fl_waterbody)

  ## read and plot result:
  waterbodies <- read_stars(fl_waterbody) |> suppressWarnings()
  plot(waterbodies, rgb = 1:3, main = "Water bodies")
}

## ----land-use, eval=eval_chunks-----------------------------------------------
if (dse_has_client_info()) {
  evalscript <-
    dse_sh_get_custom_script("/sentinel-2/land_use_with_linear_discriminant_analysis/")
  
  ## destination file:
  fl_landuse <- tempfile(fileext = ".tiff")
  
  ## send request and download result:
  dse_sh_process(input, output, evalscript, fl_landuse)

  ## read and plot result:
  landuse <- read_stars(fl_landuse) |> suppressWarnings()
  plot(landuse, rgb = 1:3, main = "Land use")
}

