#!/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)

#Set relevant file paths
curr_file_path <- rstudioapi::getSourceEditorContext()$path
cwd <- dirname(curr_file_path)
setwd(cwd)

py_file_path<-file.path("..", "..", "PSI", "0_build_fake_data.py")
data_dir <- file.path("example_data")

# The data pre-process stage has not yet been converted to R.
# This step runs the 0_build_fake_data file in python.
if (!file.exists(file.path(data_dir, "psi_data0.csv")) ||
  !file.exists(file.path(data_dir, "psi_data1.csv")) ||
  !file.exists(file.path(data_dir, "psi_data2.csv"))) {
  py_run_file(py_file_path)
}

tb <- import("tripleblind")

run_id <- tb$util$read_run_id()

tb$initialize(api_token <- tb$config$example_user1[["token"]])

result <- tryCatch(
  {
    print("Uploading 'JPM Customers' to organization-one's Access Point...")
    asset_0 <- tb$Asset$position(
      file_handle = file.path(data_dir, "psi_data0.csv"),
      name = paste("JPM Customers-", run_id, sep = ""),
      desc = "Fictional JPM account identifiers.",
      is_discoverable = TRUE,
    )
  },
  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, ""))
      cat("\n")
      quit(save = "ask")
    } else {
      if (err_type == "TripleblindAssetAlreadyExists") {
        print(paste("Asset 'JPM Customers-", run_id, "' already exists, change value in run_id.txt to make it unique.'", sep = ""))
      }
    }
  }
) # end trycatch

session_org_2 <- tb$Session(
  api_token = tb$config$example_user2[["token"]], from_default = TRUE
)

result <- tryCatch(
  {
    print("Uploading 'PNB Customers' to organization-two's Access Point...")
    asset_1 <- tb$Asset$position(
      file_handle = file.path(data_dir, "psi_data1.csv"),
      name = paste("PNB Customers-", run_id, sep = ""),
      desc = "Fictional PNB Customers.",
      is_discoverable = TRUE,
      session = session_org_2
    )

    if (tb$config$create_agreements_on_example_input_assets) {
      # For this example we will attach an Agreement to the datasets.  This
      # agreement makes the dataset available to the other team,
      # meaning the PSI step will not require the dataset owner to
      # explicitly grant permission for use.
      asset_1$add_agreement(
        with_team = tb$config$example_user1[["team_id"]],
        operation = tb$Operation$PRIVATE_SET_INTERSECTION,
        session = session_org_2
      )
      print("Created Agreement")
    }
  },
  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, ""))
      cat("\n")
      quit(save = "ask")
    } else {
      if (err_type == "TripleblindAssetAlreadyExists") {
        print(paste("Asset 'PNB Customers-", run_id, "' already exists, change value in run_id.txt to make it unique.'", sep = ""))
      }
    }
  }
) # end trycatch

session_org_3 <- tb$Session(
  api_token = tb$config$example_user3[["token"]], from_default = TRUE
)

result <- tryCatch(
  {
    print("Uploading 'Brokerage licenses' to organization-three's Access Point...")
    asset_2 <- tb$Asset$position(
      file_handle = file.path(data_dir, "psi_data2.csv"),
      name = paste("Broker licenses-", run_id, sep = ""),
      desc = "Fictional broker's licenses.",
      is_discoverable = TRUE,
      session = session_org_3
    )

    if (tb$config$create_agreements_on_example_input_assets) {
      asset_2$add_agreement(
        with_team = tb$config$example_user1[["team_id"]],
        operation = tb$Operation$PRIVATE_SET_INTERSECTION,
        session = session_org_3
      )
      print("Created Agreement")
    }
  },
  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, ""))
      cat("\n")
      quit(save = "ask")
    } else {
      if (err_type == "TripleblindAssetAlreadyExists") {
        print(paste("Asset 'Brokerage licenses-", run_id, "' already exists, change value in run_id.txt to make it unique.'", sep = ""))
      }
    }
  }
) # end trycatch

print("Data is in position.")
