#' @title Generate provenance for Spatial Extent definition
#' @description Generate provenance information of the spatial coordinates of a climate data object in s2dv_cube format. Returns a graph containing a single SpatialExtent node. 
#' @param data The dataset containing spatial coordinates.
#' @param type The type of dataset (fcst, hcst, obs)
#' @param Reg Logical indicating if the operation is for regriddinging.
#' @param Cal Logical indicating if the operation is for calibration.
#' @param Downsc Logical indicating if the operation is for downscaling.
#' @return A list containing the graph and the parent node name.
#' @import igraph
#' @examples
#' # Example usage:
#' getSpatialExtent(data, type, Reg = TRUE)
#' getSpatialExtent(data, type, Cal = TRUE)
#' getSpatialExtent(data, type, Downsc = TRUE)
#' getSpatialExtent(data, type)

getSpatialExtent<-function(data, type, Reg=FALSE, Cal=FALSE, Downsc=FALSE){

  graph<-make_empty_graph(0)
  ymax<-as.numeric(data[[type]]$coords$lat)[[length(as.numeric(data[[type]]$coords$lat))]]
  ymin<-as.numeric(data[[type]]$coords$lat)[[1]]
  xmax<-as.numeric(data[[type]]$coords$lon)[[length(as.numeric(data[[type]]$coords$lon))]]
  xmin<-as.numeric(data[[type]]$coords$lon)[[1]]
  resY<-abs(as.numeric(data[[type]]$coords$lon)[[2]]-as.numeric(data[[type]]$coords$lon)[[1]])
  yunits<-attr(data[[type]]$attr$Variable$metadata$longitude,"variables")$lon$units
  resX<-abs(as.numeric(data[[type]]$coords$lat)[[2]]-as.numeric(data[[type]]$coords$lat)[[1]])
  xunits<-attr(data[[type]]$attr$Variable$metadata$latitude,"variables")$lat$units



  if(Reg){
    spatextent.nodename <- paste0("SpatialExtent_","Reggriding")
  }else if(Cal){
    spatextent.nodename <- paste0("SpatialExtent_","Calibration",type)
  }else if(Downsc){
    spatextent.nodename <- paste0("SpatialExtent_","Downscaling",type)
  }else{
    spatextent.nodename <- paste0("SpatialExtent_","DatasetSubset_",type)
  }
  

  graph<- add_vertices(graph,
                        nv = 1,
                        name = spatextent.nodename,
                        label = "SpatialExtent",
                        className = "ds:HorizontalExtent",
                        attr = list("ds:xmin" = xmin,
                                    "ds:xmax" = xmax,
                                    "ds:ymin" = ymin,
                                    "ds:ymax" = ymax,
                                    "ds:hasHorizontalResX" = resX,
                                    "ds:hasHorizontalResY" = resY,
                                    "ds:hasProjection:"=NULL,
                                    "ds:withUnits"=paste0(paste0("X:",names(xunits)),"  ", paste0("Y:",names(yunits)))
                                    #"ds:hasProjection" = proj,
                                    )
                       )
  
  return(list("graph"=graph, "parentnodename"=spatextent.nodename))
}
            