library("shiny")
library("threejs")
library("MASS")

# Create variables to perform PCA
set.seed(1)
if(!exists("xdata")) {xdata <- cbind(mvrnorm(n = 800,c(5,4,-3),matrix(c(2,1.9,1.5,1.9,7,0.9,1.5,0.9,6),3,3)),mvrnorm(n = 800,c(-0.6,2),matrix(c(5,0,0,3),2,2)))
xdata <- cbind(xdata,xdata[,1]*9+xdata[,2]*2+rnorm(800,0,7),-xdata[,3]*2+xdata[,5]*6+rnorm(800,0,2),xdata[,2]*7+xdata[,4]*10+rnorm(800,0,10))}

# Create name for variables
numVar = ncol(xdata)
nameX = matrix(0,numVar,1)
for (j in 1:numVar) {
  nameX[j,1] = paste(c("X ",as.character(j)), collapse = '')
}


shinyServer(function(input, output){
  
  # Example_data is a reactive variable
  example_data <- reactive({
	aux = seq(1:length(nameX)) # auxiliar vector 1,2,3,...,length(nameX)
	# Select data according to label name selected following nameX
	xvar <- xdata[,aux[nameX==input$xvar]]
	yvar <- xdata[,aux[nameX==input$yvar]]
	zvar <- xdata[,aux[nameX==input$zvar]]
	example_data <- cbind(xvar,yvar,zvar)
  })
  
  # PCA_data is a reactive variable: is the Example_data in principal component space
  PCA_data <- reactive({
    PCA_data <- prcomp(example_data())  
  })
  
  # Interactive 3D scatter plot
  output$scatterplot <- renderScatterplotThree({
    num.ticks <- input$nticks
    if(num.ticks==0) num.ticks <- NULL
    else num.ticks <- rep(num.ticks,3)
    color <- rep(rainbow(input$colors),length.out=nrow(example_data()))
    sizes <- rep(c(0.5, 1, 2)[1:input$sizes], length.out=nrow(example_data()))
    labs <- sprintf("x=%.2f, y=%.2f, z=%.2f", example_data()[,1], example_data()[,2], example_data()[,3])
    scatterplot3js(x=example_data(),
                   num.ticks=num.ticks,
                   color=color,
                   size=sizes,
                   labels=labs,
                   label.margin="80px 10px 10px 10px",
                   renderer=input$renderer,
                   grid=input$grid)
  })
  # Interactive 3D scatter plot for PCA data
  output$scatterplotPCA <- renderScatterplotThree({
    num.ticks <- input$nticks
    if(num.ticks==0) num.ticks <- NULL
    else num.ticks <- rep(num.ticks,3)
    color <- rep(rainbow(input$colors),length.out=nrow(PCA_data()$x))
    sizes <- rep(c(0.5, 1, 2)[1:input$sizes], length.out=nrow(PCA_data()$x))
    labs <- sprintf("x=%.2f, y=%.2f, z=%.2f", PCA_data()$x[,1], PCA_data()$x[,2], PCA_data()$x[,3])
    scatterplot3js(x=PCA_data()$x,
                   num.ticks=num.ticks,
                   color=color,
                   size=sizes,
                   labels=labs,
                   label.margin="80px 10px 10px 10px",
                   renderer=input$renderer,
                   grid=input$grid)
  })
  
  output$view <- renderTable({
    head(PCA_data()$rotation)})
  }
)
