#!/usr/bin/env Rscript
# Copyright (c) TripleBlind Holdings, Inc. Confidential and Proprietary. All rights reserved.

# Install required packages if not already installed
RequiredPackages <- c("reticulate","stringr")
for (i in RequiredPackages) { #Installs packages if not yet installed
    if (!require(i, character.only = TRUE)) install.packages(i)
}

# Load packages
library(reticulate)
library(stringr)

tb <- import("tripleblind")

tb$initialize(api_token = tb$config$example_user2[["token"]])
tb$util$set_script_dir_current()
run_id <- tb$util$read_run_id()

result <- tryCatch(
  {
    org_name <- tb$config$example_user2[["name"]]
    print(paste("Uploading example dataset to ", org_name, "'s access point...", sep = ""))

    asset_0 <- tb$asset$CSVDataset$create(
      datafile = "data.csv",
      name = paste("Blind_Sample-", run_id, sep = ""),
      desc = "Dataset for the Blind_Sample example.",
      header = list("name", "is_alive", "age", "traffic_tickets"),
      is_discoverable = TRUE
    )

    if (tb$config$create_agreements_on_example_input_assets) {
      asset_0$add_agreement(
        with_team = tb$config$example_user1[["team_id"]],
        operation = tb$Operation$BLIND_SAMPLE
      )
      print(paste("Created access Agreement with ", tb$config$example_user1[["name"]], sep = ""))
    }
  },
  error = function(err) {
    err_type <- str_extract(err[[1]], "TripleblindAssetAlreadyExists") # err is a list

    if (is.na(err_type[[1]])) {
      print(paste("An error occurred: ", err, ""))
    } else {
      if (err_type == "TripleblindAssetAlreadyExists") {
        print(paste("An asset named 'Blind_Sample-", run_id, "' already exists.", sep = ""))
        print("Change run_id.txt to make it unique.")
      }
    }

    quit(save = "ask")
  }
) # end trycatch

print("Data is in position.")
