# server.R
 palette(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
  "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"))
 pckg = c("UsingR","rgl","devtools","shiny","shinyRGL") 
 
 # Function that install a packege if this not exist
  is.installed <- function(mypkg){
    is.element(mypkg, installed.packages()[,1])
  } 
  for(i in 1:length(pckg)) {
    if (!is.installed(pckg[i])){
      install.packages(pckg[i])
    }
  }
 # Load a library if this is not loeaded
 for(i in 1:length(pckg)) {
   require(package = pckg[i], character.only = TRUE)
 }
  
  # load data
  numVar = 20
  nameX = matrix(0,numVar,1)
  for (j in 1:numVar) {
    nameX[j,1] = paste(c("Sample ",as.character(j)), collapse = '')
  }

server <- function(input, output, session) {
  X <- reactive({
    ## Generate random samples from num Gaussians specified by the user
    
    mu_vector = c(-5,-4,-3,-2,-1,0,1,2,3,4,5)
    Sigma1 <- matrix(c(1,1.5,1.5,3),2,2)
    Sigma2 <- matrix(c(0.2,0.1,0.1,0.15),2,2)
    Sigma3 <- matrix(c(0.5,0.2,0.2,0.8),2,2)
    Sigma4 <- matrix(c(0.8,0.6,0.6,0.85),2,2)
    Sigma5 <- matrix(c(1,0.4,0.4,0.65),2,2)
    Sigma6 <- matrix(c(1.2,0.1,0.1,0.98),2,2)
    Sigma7 <- matrix(c(1.3,0.7,0.7,1.6),2,2)
    Sigma8 <- matrix(c(1.5,0.9,0.9,1.5),2,2)
    Sigma9 <- matrix(c(1.7,1,1,1.9),2,2)
    Sigma10 <- matrix(c(1.9,0.3,0.3,1.4),2,2)
    Sigma = cbind(Sigma1,Sigma2,Sigma3,Sigma4,Sigma5,Sigma6,Sigma7,Sigma8,Sigma9,Sigma10)
    numGaussian = input$NumGaussians
    X<-matrix(list(), numVar, 1)
    nameX = matrix(0,numVar,1)
    for (j in 1:numVar) {
      for(i in 1:numGaussian) {
        k = sample(seq(2,ncol(Sigma),by = 2), 1)
        aux = mvrnorm(n = 150,c(sample(mu_vector, 1),sample(mu_vector, 1)),Sigma[1:2,(k-1):k])
        if (i == 1) xj = aux
        xj = rbind(aux,xj)
      }
      X[[j,1]] = xj
      nameX[j,1] = paste(c("Sample ",as.character(j)), collapse = '')
    }
    X = X
  })
  
  # Combine the selected variables into a new data frame
    selectedData <- reactive({
    ## Generate random samples from num Gaussians specified by the user
    prova = input$Sample
    aux = seq(1:length(nameX))
    sel = aux[nameX==prova]
    selectedData = data.frame(X()[[sel,1]])
  })

  clusters <- reactive({
    Mclust(selectedData())
  })
  
  output$plot2 <- renderPlot({
    plot(selectedData(), pch = 20, cex = 3)
  })
  output$plot1 <- renderPlot({
    plot(selectedData(), col=clusters()$classification, pch = 20, cex = 3)
    points(t(clusters()$parameters$mean), pch = 4, cex = 4, lwd = 4)
  })
}