require(pacman)
source('../R/utils.R')

step_imp <- function(x, y, ...) {
  p_load(caret)
  
  data = data.frame(x, y)
  
  if (class(y) == 'factor') {
    data$y = as.numeric(y) - 1
    base.mod <- glm(y ~ 1, data = data, family = binomial(link = "logit"))
    all.mod <- glm(y ~ .^2, data = data, family = binomial(link = "logit"))
  } else {
    base.mod <- lm(y ~ 1, data = data)
    all.mod <- lm(y ~ .^2, data = data)
  }
  stepMod <- step(base.mod, 
                  scope = list(lower = base.mod, 
                               upper = all.mod), 
                  direction = "both", trace = 0, steps = 1000)  # perform step-wise algorithm
  

  imp = varImp(stepMod, scale = TRUE)
  imp = import_xvars(imp)
  
  list(errRank = imp_measure(imp[xvars]), 
       imp = imp_scale(imp[xvars]),
       oimp = imp[xvars],
       mi = names(which.max(imp)))
}
