if(!suppressMessages(suppressWarnings(library('jsonlite', logical = T)))){
  install.packages('jsonlite')
  library(jsonlite)
}
if(!suppressMessages(suppressWarnings(library('jsonlite', logical = T)))){
  install.packages('remotes')
  library(remotes)
}
needs <- fromJSON(input[[1]])
# needs <- fromJSON('[{"pkg": "haven", "version": "2.1.1"}, {"pkg": "mde", "version": "0.1.8"}]')
mdePath <- input[[2]]
# mdePath <- 'D:\\Projects\\mde\\dev\\MDE\\r-package\\mde_0.1.8.tar.gz'

needsPackage <- needs$pkg

if (length(needsPackage)) {
  
  #. install the missing packages
  loaded <- suppressMessages(suppressWarnings(sapply(needsPackage, 
                                                     library, character = T, logical = T)))
  if (any(!loaded)) {
    
    missing <- needsPackage[!loaded]
    cat("installing packages:n")
    cat(missing, sep = "n")
    
    # package mde is not availabe in cran, install from local path
    if('mde' %in% missing){
      missing <- missing[missing != 'mde']
      utils::install.packages(mdePath, repos = NULL, type="source")
    }
    
    utils::install.packages(missing, repos = "http://cran.rstudio.com/", 
                            quiet = T)
  }
  suppressMessages(suppressWarnings(sapply(needsPackage, library, 
                                           character = T)))
  
  #. check the installed package versions and update the packages if required.
  packageInfo <- utils::installed.packages()
  
  installedPackages <- packageInfo[, "Package"]
  
  needsVersion <- needs$version
  
  installed <- needsPackage %in% installedPackages
  
  compared <- mapply(utils::compareVersion, needsVersion[installed], 
                     packageInfo[needsPackage[installed], "Version"])
  
  #. method to update the package
  fnUpdatePackage <- function(pkg, pkg_version) {
    tryCatch({
      remove.packages(pkg,  .libPaths())
      if(pkg == 'mde'){
        utils::install.packages(mdePath, repos = NULL, type="source")
      } else {
        remotes::install_version(pkg, version = pkg_version, repos = "http://cran.us.r-project.org")
      }
      return ("success")
    },error=function(cond) {
      if(pkg == 'mde'){
        utils::install.packages(mdePath, repos = NULL, type="source")
      } else {
        utils::install.packages(pkg)
      }
      return("error")
    },
    warning=function(cond) {
      if(pkg == 'mde'){
        utils::install.packages(mdePath, repos = NULL, type="source")
      } else {
        utils::install.packages(pkg)
      }
      return("warning")
    })
  }
  
  #. find the version mismatch and update the package
  updateResp <- mapply(fnUpdatePackage, needs$pkg[installed][compared != 0], needs$pkg[installed][compared != 0], SIMPLIFY=FALSE)

  return('success')

} else {
  return('no packages')
}



