## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
tryCatch({
  Sys.setlocale("LC_ALL", "English")
})
library(ggplot2)
theme_set(theme_light())
dataset_form <- NULL
request <- NULL
job <- NULL
file_result <- NULL
filename <- "skip"

## ----token--------------------------------------------------------------------
library(CopernicusClimate)

message(
  "The machine that rendered this vignette ",
  ifelse(
    cds_token_works(), "has", "does not have"),
  " a working token")


## ----get-licence, message=FALSE-----------------------------------------------
library(dplyr)

tryCatch({
  licence_info <-
    cds_dataset_form("reanalysis-era5-pressure-levels") |>
      filter(name == "licences")

  licence_info <- licence_info$details[[1]]$details$licences[[1]]
  print(licence_info)
}, error = \(e) message("Failed to get licence info"))

## ----listing------------------------------------------------------------------
tryCatch({
  cds_list_datasets()
}, error = \(e) message("Failed to retrieve datasets"))

## ----search-------------------------------------------------------------------
tryCatch({
  cds_search_datasets(search = "rain", keywords = "Temporal coverage: Future")
}, error = \(e) message("Failed to search for datasets"))

## ----dataset-form-------------------------------------------------------------
tryCatch({
  dataset_form <-
    cds_dataset_form("reanalysis-era5-pressure-levels")
  dataset_form
}, error = \(e) message("Failed to retrieve request form"))

## ----possible-values, eval=!is.null(dataset_form)-----------------------------
values <-
  dataset_form |>
  filter(name == "pressure_level") |>
  pull("details")

values[[1]]$details$values |> unlist()

## ----full-request-------------------------------------------------------------
tryCatch({
  request <- cds_build_request("reanalysis-era5-pressure-levels")
  summary(request)
}, error = \(e) message("Failed to build request"))

## ----specific-request---------------------------------------------------------
tryCatch({
  request <- cds_build_request(
    "reanalysis-era5-pressure-levels",
    variable       = "temperature",
    pressure_level = "1000",
    year           = "2025",
    month          = "01",
    day            = "01",
    area           = c(n = 60, w = -5, s = 40, e = 10),
    data_format    = "netcdf")
  summary(request)
}, error = \(e) message("Failed to build the request"))

## ----estimate-full------------------------------------------------------------
if (cds_token_works()) {
  tryCatch({
    cds_estimate_costs("reanalysis-era5-pressure-levels")
  }, error = \(e) message("Failed to estimate costs"))
} else {
  message("You need a working token to estimate costs")
}

## ----estimate-detailed, eval=!is.null(request)--------------------------------
if (cds_token_works()) {
  tryCatch({
    cds_estimate_costs(request)
  }, error = \(e) message("Failed to estimate costs"))
} else {
  message("You need a working token to estimate costs")
}

## ----submit, message=FALSE----------------------------------------------------
if (cds_token_works()) {
  tryCatch({
    job <-
      cds_submit_job(request)
    job
  }, error = \(e) message("Failed to submit job"))
} else {
  message("You need a working token to submit a request")
}

## ----job-status, eval=!is.null(job)-------------------------------------------
if (cds_token_works()) {
  cds_list_jobs(job$jobID)
} else {
  message("You need a working token to get a job status")
}

## ----download, message=FALSE, eval=!is.null(job)------------------------------
filename <- "result.nc"
if (cds_token_works()) {
  tryCatch({
    file_result <- cds_download_jobs(job$jobID, tempdir(), filename)
  }, error = \(e) message("Failed to download job"))
} else {
  message("Downloading data only works with a valid token")
}

## ----plot, fig.width=7, fig.height=3, message = FALSE, fig.alt="Plot created from downloaded data"----
fn <- file.path(tempdir(), filename)

if (file.exists(fn)) {
  
  library(stars)
  library(ggplot2)
  
  result <- read_mdim(fn)
  
  ggplot() +
    geom_stars(data = result) +
    coord_sf() +
    facet_wrap(~strftime(as.POSIXct(valid_time), "%H:%M"), nrow = 3) +
    scale_fill_viridis_c(option = "turbo") +
    labs(x = NULL, y = NULL, fill = "Temperature [K]") +
    theme(axis.text = element_blank())

} else {
  message("File wasn't downloaded")
}

