# install.packages(devtools)
# library(devtools)
# devtools::install_github("metaclip/metaclipR")
library(metaclipR)

# mamba install -y -c conda-forge -c r -c defaults -c santandermetgroup r-climate4r
library(climate4R.climdex)
# Also available via mamba...
library(transformeR)
library(loadeR)
library(visualizeR)

# To see some pre-defined datasets available in METACLIP
# knownClassIndividuals(classname = "GCM", vocabulary = "datasource")
# head(showUDGDatasources())
# showUDGDatasources()[7, ]
# getIndividualClass("E-OBS")

# https://opendap.deltares.nl/thredds/dodsC/opendap/knmi/uurgeg/uurgeg_240_2011-2020.nc.html
uur.url <- "http://opendap.deltares.nl/thredds/dodsC/opendap/knmi/uurgeg/uurgeg_240_2011-2020.nc"

# Load a dataset
# TODO: use something from SUNSET or BSC (publicly available)
# KNMI = Koninklijk Nederlands Meteorologisch Instituut
#      = Royal Netherlands Meteorological Institute
# UUR = Uurgegevens van het weer in Nederland
#     = Hourly data of the weather in the Netherlands
metadata.uur <- metaclipR.Dataset(
  Dataset.name = "E-uur",
  DataProvider = "KNMI",
  DataProvider.URL = uur.url,
  Dataset.subclass = "ObservationalDataset",
  Project = "UUR", # ?
  ModellingCenter = "KNMI"
)

# Subsetting
lon <- c(0, 5)
lat <- c(45, 60)
# tasmax <- loadGridData(
#   dataset = uur.url,
#   var = "rain",
#   season = 1:12,
#   years = 2011:2020,
#   lonLim = lon,
#   latLim = lat
# )

# Climatology
# metadata.uur.SU <- metaclipR.Climatology(
#   graph = metadata.uur.SU,
#   arg.list = list(
#     clim.fun = list(
#       FUN = "mean",
#       na.rm = TRUE
#     )
#   )
# )

# Anomalies calculation

# metadata.rcp85 <- metaclipR.AnomalyCalculation(
#   graph = metadata,
#   package = "transformeR",
#   version = "1.3.3",
#   fun = "scaleGrid",
#   arg.list = list(
#     clim.fun = list(FUN = mean, na.rm = TRUE),
#     base = "SU.clim",
#     time.frame = "none",
#     by.member = TRUE,
#     spatial.frame = "gridbox"
#   ),
#   referenceGraph = metadata.BSC.SU
# )

# Plot the dataset
# dev.off()
plot(metadata.uur$graph)

# Serialize the dataset as JSON-LD
graph2json(metadata.uur$graph, "/tmp/graph.json")
