source('import.R')

#* @filter cors
function(req, res) {
  res$setHeader("Access-Control-Allow-Origin", "*") 
  if (req$REQUEST_METHOD == "OPTIONS") {
    res$setHeader("Access-Control-Allow-Methods","*")
    res$setHeader("Access-Control-Allow-Headers", req$HTTP_ACCESS_CONTROL_REQUEST_HEADERS)
    res$status <- 200 
    return(list())
  } else {
    plumber::forward()
  }
}

#* Endpoint - import datasets
#* @post /import
function(req, res){
  tryCatch({
    
    # get params from request body
    params <- fromJSON(req$postBody)
    filepath = params$filepath
    type = params$type
    fileId = params$fileId
    freqLimit = params$freqLimit      
    
    res$body <- (toJSON(fnImportDataset(filepath, type, fileId, freqLimit),pretty=TRUE,force=TRUE,auto_unbox=TRUE,digits=22))
    return(res)
  }, warning = function(war) {
    res$body <-  (toJSON(result='warning', message= paste('warning >> ',war)))
    return(res)
  }, error = function(err) {
    res$body <- (toJSON(result='error', message= paste('error >> ',err)))
    return(res)
  })
}

#* Endpoint - import datasets and write to CSV
#* @post /writeCSV
function(req, res){
  tryCatch({
    
    # get params from request body
    params <- fromJSON(req$postBody)
    filepath = params$filepath
    type = params$type
    csvpath = params$csvPath    
    
    res$body <- (toJSON(fnWriteCSV(filepath, type, csvpath)))
    return(res)
  }, warning = function(war) {
    res$body <-  (toJSON(result='warning', message= paste('warning >> ',war)))
    return(res)
  }, error = function(err) {
    res$body <- (toJSON(result='error', message= paste('error >> ',err)))
    return(res)
  })
}


#* Endpoint - stop current R session
#* @get /stop
function(){
    q()
}

