### import.test.R
###------------------------------------------------------------------------------------------
### What: script to be executed from the health check page(test R env)
### Time-stamp: <2017-06-26 11:21:27 assyst>
###-------------------------------------------------------------------------------------------

## Input Parameters
# dataset file path 
fileName <- input[[1]]
# dataset type STATA/SPSS/CSV
type <- input[[2]]
# libary path (R library path embedded in MDE)
libPath <- input[[3]]
# include R session info in the output
includeSessionInfo <- input[[4]]

# fileName <- 'D:\\MetadataEditorSource\\MetadataEditor\\Sample Data\\in\\caseA.dta'
# type <- "dta"
# libPath <- 'D:\\MetadataEditorSource\\MetadataEditor\\MetadataEditor.Main\\MetadataEditor-win32-x64\\R\\library'
# includeSessionInfo <- TRUE

# load packages, if lib.location is given then load from the given location else from the default loc.
# R is not embedded in the MAC version of MDE, load packages from the default location in MAC. 
if(libPath == "MAC") {
  libPath <- NULL
  Sys.setlocale(category = "LC_ALL", locale = "UTF-8")
}
if (is.null(libPath)) {
  library(haven)
  library(labelled)
  library(plyr)
  library(stringr)
  library(jsonlite)
} else {
  .libPaths(libPath)
  library(labelled, lib.loc=libPath)
  library(haven, lib.loc=libPath)
  library(plyr, lib.loc=libPath)
  library(stringr, lib.loc=libPath)
  library(jsonlite, lib.loc=libPath)
}

# Read dataset files
if (toupper(type) == 'DTA') {
  DF_DATA <- read_dta(fileName)
} else if (toupper(type) == 'SAV') {
  DF_DATA <- read_spss(fileName)
}

# get R env details
if (includeSessionInfo) {
    result <- list (
    libPaths=.libPaths(),
    RHOME=R.home(),
    Syslocal=Sys.getlocale(category = "LC_ALL"),
    packageVersions=data.frame(
    haven=c(packageVersion("haven")),
    labelled=c(packageVersion("labelled")),
    plyr=c(packageVersion("plyr")),
    stringr=c(packageVersion("stringr")),
    jsonlite=c(packageVersion("jsonlite")),
    readr=c(packageVersion("readr")),
    stringi=c(packageVersion("stringi")),
    opencpu=c(packageVersion("opencpu")),
    mde=c(packageVersion("mde"))),
    rowCount=nrow(DF_DATA)
 )
} else {
    result <- list(
    libPaths=.libPaths(),
    RHOME=R.home(),
    rowCount=nrow(DF_DATA)
 )
}

varjson <- toJSON(result,pretty=TRUE,force=TRUE)

# return number of records
return (varjson)
