### convert.tsv.R
###------------------------------------------------------------------------------------------
### What: script to convert tab separated values to csv format, MDE uses csv format to store the data,
###       While importing nesstar study, tsv data file should be converted to csv format
### Time-stamp: <2018-01-17 11:21:27 assyst>
###-------------------------------------------------------------------------------------------


## input parameters
# file to be converted to csv format
csvPath <- input[[1]] 
# variable info(If column class is not specified, R guess the data type while reading csv and leads to leading zero missing issue)
listOfVariables <- fromJSON(input[[2]]) 
# libary path (R library path embedded in MDE)
libPath <- input[[3]]
# directory to load functions
workingDirectory <- input[[4]]

# csvPath <- 'D://MetadataEditorSource//MetadataEditor//MetadataEditor.Import//test_data//input//csv//F1.csv'
# listOfVariables <- fromJSON([
#   {"name":["uqnr"],"internalName":["uqnr"],"type":["character"]},{"name":["personnr"],"internalName":["personnr"],"type":["character"]},
#   {"name":["psu"],"internalName":["psu"],"type":["character"]},{"name":["prov"],"internalName":["prov"],"type":["numeric"]}
#])
# libPath <- NULL


# R is not embedded in current MAC version, Hence use default path to load the libraries
if(libPath == "MAC") {
  libPath <- NULL
  Sys.setlocale(category = "LC_ALL", locale = "UTF-8")
}

if (is.null(libPath) || libPath == '') {
  # use default library path to load packages
  library(haven)
  library(jsonlite)
  library(readr)
} else {
  # load packages from the path passed as parameter
  .libPaths(libPath)
  library(haven, lib.loc=libPath)
  library(jsonlite, lib.loc=libPath)
  library(readr, lib.loc=libPath)
}

# Set working directory
setwd(workingDirectory);
# Load functions
source("fn.common.utilities.R")

# read data file
DF_DATA <- read.datafile(listOfVariables, file=csvPath, type="tsv")

## write csv with the options given below
# file  - file path with encoding scheme
# quote - non numeric values should be enclosed in quotes
# na    - na will be replaced with *
write_csv(DF_DATA, csvPath, na = "*", append = FALSE) 

return(0)