source("provenance/R/prov_visualization.R")

prov_Visualization <- function(recipe, graph, outdirs) {
  
  #fcst definition
  if (!is.null(data$fcst)) {
    graph_fcst <- prov_visualization(recipe, data, graph, type = "fcst",
                                     outdirs)
  }

  #hcst definition (Dataset+Datasubset)
  graph_hcst <- prov_visualization(recipe, data, graph, type = "hcst", outdirs)
  
  #obs definition
  parentnodename_obs <- graph$parentnodename$parentnodename_obs

  #Command Call and output definition
  if (!is.null(data$fcst)) {
    graph <- my_union_graph(graph_fcst$graph, graph_hcst$graph)

    graph <- list("graph" = graph,
                  "parentnodename" =
                    list(
                         "parentnodename_fcst" = graph_fcst$parentnodename,
                         "parentnodename_hcst" = graph_hcst$parentnodename,
                         "parentnodename_obs" = parentnodename_obs))

  } else {
    graph <- graph_hcst$graph

    graph <- list("graph" = graph,
                  "parentnodename" =
                    list(
                         "parentnodename_hcst" = graph_hcst$parentnodename,
                         "parentnodename_obs" = parentnodename_obs))
  }
  
  message("INFO  ", "[", Sys.time(), "]",
          " Provenance correctly generated for the Visualization module")
  message("INFO  ", "[", Sys.time(), "]",
          " JSON provenance metadata correctly embedded on the images")

  #Name of the generated JSON according to recipe values
  trimmed_dir <- dirname(recipe$Run$output_dir)
  main_dir <- paste0(trimmed_dir, "/outputs", "/provenance/")
  recipe_model <- paste0("sys-",
                         gsub('\\.', '', recipe$Analysis$Datasets$System$name))
  recipe_split <- paste0("_ref-", recipe$Analysis$Datasets$Reference$name,
                         "_var-", recipe$Analysis$Variables$name,
                         "_reg-", recipe$Analysis$Region$name,
                         "_sdate-", recipe$Analysis$Time$sdate)

  json_name <- paste0("main_provenance", "_", recipe_model, recipe_split)

  #Convert from igraph to JSON format and store in the output directory
  graph2json(graph$graph, output.file = paste0(main_dir,
                                               json_name,  ".json"))
  return(graph)
}
