#!/usr/bin/env Rscript
## A class that contains bam file information
## Copyright 2014, Sahil Seth, all rights reserved
## sahil.seth@me.com
## A few functions to supplement those already in this package.
#### -----------------------


verbose=FALSE

##cat(".")
### in myModul.R
### numeric: _N
### character: _C
### logical: _L
get_params <- function(paramPairs){
  func <- as.character(paramPairs[1])
  if(length(func) == 0) return(help())
  args <- formals(func)
  paramPairs <- paramPairs[grep("=", paramPairs)] ## get those with =
  if(verbose) cat("We have",length(paramPairs),"parameters\n")
  for(param in paramPairs){
    temp <- unlist(strsplit(param, "="));
    nm = temp[1]
    value=temp[2]
    value <- strsplit(value,",")[[1]] #handling those with , in value.. for multiple R values
    ## if function supports ... need to pass ALL arguments
    if(sum(names(args) %in% "...")){
      message("Adding ", nm, ":", value)
      args <- c(args, list(nm = value))
    }
    if(class(args[[nm]]) == "numeric" ){
      args[[nm]] = as.numeric(value)
    }else if(class(args[[nm]]) %in% c("character", "name" )){
      args[[nm]] = as.character(value)
    }else if(class(args[[nm]]) %in% c("logical")){
      args[[nm]] = as.logical(value)
    }else if(class(args[[nm]]) %in% c("list")){
      args[[nm]] = as.list(value)
    }
    ## if(verbose) cat("Working on", param)
  }
  return(as.list(args))
}


flow_help <- function(){
  cmds <- matrix(c(
    'status',   'Detailed status of a flow',
    'kill_flow',     'Kill the flow, upon providing working directory'
  ), byrow=T, ncol=2)
  cat(sprintf("Usage: flowr function [arguments]\n\n"))
  cat("This interface allows shell access to all functions in package flowr (and beyond).",
      "\nFunctions where the arguments are simple objects like numeric/character/logical can be called.",
      "\nSome example functions (all R functions are applicable):\n")
  cat(sprintf("  %-15s %s\n", cmds[,1], cmds[,2]), sep="")
  cat(sprintf("\nPlease use 'flowr function -h' to obtain further information about the usage of the 'function'.\n"))
}


library(flowr, quietly=!verbose, warn.conflicts=verbose)


args <- commandArgs(trailingOnly = TRUE)

## -------------- Load the required package
if(grepl("::", args[1])){
  pkg <- gsub("(.?)::.*", "\\1", args[1])
  cat("loading pkg:", pkg, "\n");
  library(pkg, character.only = TRUE)
  args[1] = gsub(".*::(.*)", "\\1", args[1])
}

if(is.na(args[1])) {
  flow_help()
}else if(args[1] == "-h"){
  flow_help()
}else if(is.na(args[2])){
  help(args[1])
}else if(args[2] == "-h"){
  help(args[1])
}else{
  params <- get_params(args)
  if(verbose){
    cat("\nStarting",args[1],"with params\n",
        paste(names(params),unlist(params),sep=": ",
              collapse="\n"),"\n")
    #print(args)
    print(class(params))
  }
  out <- do.call(as.character(args[1]), args = params)
}



