library(shiny)
library(lattice)
library(RColorBrewer)
library(parathyroidSE)
data(parathyroidGenesSE)

shinyServer(function(input, output) {

  dataset <- reactive({
    ## get and transform data
    m0 <- assay(parathyroidGenesSE)
    m <- switch(input$transform,
                none=m0,
                asinh=asinh(m0),
                sqrt=sqrt(m0),
                log1=log(m0 + 1))
    ## cluster distances and determine order
    ## as in heatmap()
    cor_m <- cor(m)
    ddr <- as.dendrogram(hclust(dist(cor_m)))
    w <- rowMeans(cor_m)
    ddr <- reorder(ddr, w)
    o <- order.dendrogram(ddr)
    ## return re-ordered data
    parathyroidGenesSE[,o]
  })

  output$overview <- renderPrint({
    print(dataset())
  })

  output$expt_data <- renderPrint({
    print(exptData(dataset())[[1]])
  })

  output$col_data <- renderTable({
    df0 <-colData(dataset())
    df <- as.data.frame(df0[, 3:8])
    rownames(df) <- df0$run
    df
  })

  output$heatmap <- renderPlot({
    m <- dataset()
    corm <- cor(assay(m))
    colnames(corm) <- colData(m)$run
    col0 <- brewer.pal(11, "RdYlGn")
    col <- colorRampPalette(col0)(100)
    print(levelplot(corm,
        cuts=length(col) - 1,
        col.regions=col,
        aspect="iso",
        xlab=NULL, ylab=NULL,
        scales=list(x=list(draw=FALSE))))
  })

})
