###############################################################################
## Author: An-Chi Ho
## Description: Script to test developments for decadal workflows. Please,
##              do not modify.
###############################################################################

source("modules/Loading/Loading.R")
source("modules/Calibration/Calibration.R")
source("modules/Skill/Skill.R")
source("modules/Saving/Saving.R")
source("modules/Visualization/Visualization.R")

library(metaclipR)
library(loadeR)
library(transformeR)

recipe_file <- "recipes/atomic_recipes/recipe_seasonal_provenance.yml"
recipe <- prepare_outputs(recipe_file)
# archive <- read_yaml(paste0(recipe$Run$code_dir, "conf/archive_decadal.yml"))$archive

# Load datasets
data <- Loading(recipe)

metadata.seas5 <- metaclipR.Dataset(
  Dataset.name = "SUNSET Sample Seasonal Dataset",
  DataProvider = "ECMWF",
  # DataProvider.URL = url,
  Dataset.subclass = "SeasonalHindcast",  # Right?
  Project = "SEAS5", # ?
  ModellingCenter = "ECMWF"
)
# TODO: Create ensemble metaclipR.Ensemble()
# Encoding provenance:  
# Calibrate datasets
calibrated_data <- Calibration(recipe, data)

# Register the calibration...
metadata_calibrated <- metaclipR.BiasCorrection(
  package="modules/Calibration/Calibration.R",
  "1.0",
  BC.method = "bias",  # from recipe
  fun = "Calibration",
  arg.list = list(
    recipe,
    data
  ),
  TrainingGraph=metadata.seas5,
  ReferenceGraph=metadata.seas5,
  graph = metadata.seas5
)

#metadata_calibrated<-embedFig(plot.fun="SpatialPlot",full.metadata=metadata_calibrated$graph, format="png", filename="test.png", width=950, height=800, res=150)

# Compute skill metrics
skill_metrics <- Skill(recipe, calibrated_data)

# Compute percentiles and probability bins
probabilities <- Probabilities(recipe, calibrated_data)

# Plot data
# Visualization(recipe, calibrated_data, skill_metrics, probabilities,
# 	      significance = T)

dev.off()
plot(metadata_calibrated$graph)
graph2json(metadata_calibrated$graph, "/tmp/graph.json")

print("OK!")