require(reshape2)

toUtime <- function(df) {
  strf <- "%Y-%m-%dT%H:%M:%S"  
  amount <- 0  
  for(i in c(1:nrow(df))) {
    df$UStart[i] <- as.numeric(as.POSIXct(df$Start[i], strf, tz="UTC"))
    df$UEnd[i] <- as.numeric(as.POSIXct(df$End[i], strf, tz="UTC"))    
  }
  return(df)
}

xod <- function(df) {
  #x order difference
  #df <- df[,-1] #get rid of time
  
  colnames(df) <- lapply(colnames(df), function(x) return(paste("fd_",x,sep="")))
  for(i in c(nrow(df):2)) {
    df[i,] <- df[i,] - df[i-1,]
  }  

  df[1,] <- 0 # zero first row
  return(df)
}

#moving average
ma <- function(df, n=20, rm.df=TRUE) {
  #remove time
  if(rm.df) df <- df[,-1]
  ma.matrix <- filter(df,rep(1/n,n),sides=1)
  ma.df <- as.data.frame(ma.matrix)
  colnames(ma.df) <- lapply(colnames(df), function(x) paste("ma_",x,sep=""))
  return(ma.df)
}

add.gt <- function(s, gt, room) {
  gt.r <- gt[gt$Location == room | gt$Event == "Unoccupied",]
  s$event <- rep(NA,nrow(s))
  for(i in c(1:nrow(gt.r))) {
    for(j in c(1:nrow(s))) {
      if(s$utime[j] >= gt.r$UStart[i] & s$utime[j] <= gt.r$UEnd[i]) {
        if(gt.r$Event[i] == "Unoccupied")
          s$event[j] <- 0
        else
          s$event[j] <- 1
      }        
    }
  }
  return(s)
}

#UNCOMMENT FOR CMDLINE
s.wide <- read.csv(commandArgs(T)[1], head=T)
gt <- read.csv(commandArgs(T)[2], head=T)
#gt <- read.csv('../gt/1.csv', head=T)
room <- commandArgs(T)[3]
outfile <- commandArgs(T)[4]
#room <- "Kitchen"
#sensor.data <- read.csv('./trl_xively_kitchen_tf.csv', head=T)
gt.f <- toUtime(gt)
#s.wide <- dcast(sensor.data, utime ~ var, mean)
s.wide <- s.wide[complete.cases(s.wide),]
#feature calculator
fd <- xod(s.wide[,names(s.wide) != "Digital_Inputs"][,-1]) #get rid of digi
sd <- xod(fd)
s.features <- cbind(s.wide, fd, sd, ma(s.wide[,names(s.wide) != "Digital_Inputs"]))
if("Digital_Inputs" %in% names(s.features)) {
    dma <- ma(s.wide[,names(s.wide) == "Digital_Inputs"], 20, FALSE)
    s.features <- cbind(s.features, 1*(dma > 0))
    names(s.features)[ncol(s.features)] <- "maDigital_Inputs"
}
#scale features
#s.scale <- cbind(utime=s.features$utime, as.data.frame(scale(s.features[,-1])))
s.set <- add.gt(s.features, gt.f, room)
write.table(s.set, outfile, quote=F, sep=",", row.names=F)
