#borrowed significant and substantial portions of code from http://bigcomputing.com/PerformanceAnalytics.R
#see youtube http://www.youtube.com/embed/0iR8Fo0jwW8 for the demo

# R/websockets example
if(any(is.na(packageDescription('caTools'))))
  stop("This demo requires the caTools package.\nRun install.packages('caTools') to install it.\n\n")
if(any(is.na(packageDescription('PerformanceAnalytics'))))
  stop("This demo requires the PerformanceAnalytics package.\nRun install.packages('PerformanceAnalytics') to install it.\n\n")
library('websockets')
library('caTools')
library('quantmod')
library('PerformanceAnalytics')
require('RJSONIO')

#w = createContext(webpage=static_text_service(htmldata))
w = createContext()

# Set up an established (initialization) callback
g = function(DATA, WS, ...)
{
  websocket_write("hello",WS)
  print("established connection")
}
setCallback("established",g, w)

# Set up a receive callback
f = function(DATA, WS, ...)
{
  #get data sent from websocket
  d = tryCatch(rawToChar(DATA),error=function(e) "")
  #convert JSON message to data.frame and eventually xts
  perf <- fromJSON(d)
  perf.df<- as.data.frame(matrix(unlist(fromJSON(d)),ncol=3,byrow=TRUE),stringsAsFactors=TRUE)
  perf.df[,2:3] <- apply(perf.df[,2:3],MARGIN=2,as.numeric)/100
  #name columns
  colnames(perf.df) <- c("date","portfolio","sp500")
  #get as xts so convert dates from %m/%d/%Y to %Y-%m-%d
  perf.xts <- as.xts(perf.df[,2:NCOL(perf.df)],order.by=as.Date(perf.df[,1],format="%m/%d/%Y"))
  f = tempfile()
  jpeg(file=f, width=850,height=500, quality=100)
  devAskNewPage(ask=FALSE)
  charts.PerformanceSummary(perf.xts, colorset = rich6equal, lwd = 2, ylog = TRUE)
  dev.off()
  p <- base64encode(readBin(f,what="raw",n=1e6))
  p <- paste("data:image/jpg;base64,\n",p,sep="")
  websocket_write(paste(p),WS)
  file.remove(f)

  #this will send the dataframe so an object of arrays
  #websocket_write(toJSON(df),WS);
  #try with matrix which sends an array of objects (d3 prefers and handles better)
  #websocket_write(toJSON(as.matrix(df)),WS)
  #websocket_write("got your data; thanks",WS)
}
setCallback("receive",f, w)


cat("\nThe web service will run until <CTRL>+C is pressed.\n")
cat("Open your local web browser to http://localhost:7681\n")
while(TRUE) {
  service(w, timeout=1000L)
  #old service(w)
  #old Sys.sleep(0.05)
}
rm(w)
gc()