# doc <- tags$html(
#   tags$head(
#     tags$title('My first page')
#   ),
#   tags$body(
#     h1('My first heading'),
#     p('My first paragraph, with some ',
#       strong('bold'),
#       ' text.'),
#     div(id='myDiv', class='simpleDiv',
#         'Here is a div with some attributes.')
#   )
# )
# cat(as.character(doc))
# 
# ##

JS_pre  <- "\n  <link rel=\"stylesheet\" href=\"/resources/demos/style.css\" />\n  <script>\n"
JS_post <- "\n  </script>\n \n<div class=\"ui-widget\">\n  <label for=\"tags\">Tags: </label>\n  <input id=\"tags\" />\n</div>\n"



INCL <- '  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>'




JS <- '
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "JaJa Binks",
      "HERE WE GO",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme",
      "New"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>
 
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags" />
</div>
'

 js_before_terms <- "\n $(function() {\n     var availableTags = ["
 js_after_terms <- " ];\n    $( \"#tags\" ).autocomplete({\n      source: availableTags\n    });\n  });"





  ## in term: 
  #    R -e "shiny::runApp('~/git/orch/src/MktingReport/FBShiny_app')"
  #    sudo R -e "shiny::runApp('/mnt/data/rprojs/FBShiny_app')"
  # 
  # In interactive
  #   shiny::runApp('~/git/orch/src/MktingReport/FBShiny_app')
  #   If needed:
  #    ingestAllRDS(as.path("~/git/orch", "./src/MktingReport/FBShiny_app/"))



  suppressPackageStartupMessages({
    library(googleVis)
    library(data.table)
    library(shiny)
  })


  ## TODO: Import function mutualToRows & dependencies

  source("funcsForShiny.r")
  source("global.r", local=FALSE)


  # ----------------------- #



  qtl = 0.99   # quantile
  howManyTopBot <- 3

  ## If qtls was not manually set
  qtls <- sort(c(qtl, 1-qtl))

  # ~~~~ 
  categ = "Label"   #  <~~~~ THIS SHOULD BE INCOMING

  getExtremesInfo(categ, qtls, howManyTopBot)

# ~~~~~~~~~~~ #

#  key(C.DT)
#  C.DT[]


#    Q[.(Tops)]
#    merge(Tops, Q, by=key(Tops))
#    DT[, keyby=key(C.DT)][.(Tops)]
#    C.DT[.(Tops)]



## Calculate 

if (FALSE)  {
## THIS WILL COME IN HANDY: 
       shinyServer(function(input, output) {
         currentFib         <- reactive({ fib(as.numeric(input$n)) })
     
         output$nthValue    <- renderText({ currentFib() })
         output$nthValueInv <- renderText({ 1 / currentFib() })
       })

   # : WILL NOT WORK 
   # : -------------------------------------------
      shinyServer(function(input, output) {
        # Will give error
        currentFib      <- fib(as.numeric(input$n))
        output$nthValue <- renderText({ currentFib })
      })
   # : 
   # : WILL WORK, but does not save execution time. 
   # : -------------------------------------------  
   # : On the other hand, if currentFib is a function that accesses 
   # :     a reactive value, and that function is called within the
   # :     reactive world, then it will work:
   # : 
      shinyServer(function(input, output) {
        # OK, as long as this is called from the reactive world:
        currentFib <- function() {
          fib(as.numeric(input$n))
        }
      
        output$nthValue <- renderText({ currentFib() })
      })

}


 # server.R
# ---------------- #
 shinyServer(function(input, output) {

  campSelected <- reactive({
    input$CID
  })

  DTMadeName <- reactive({
    ## TODO ?:  Date = FALSE
    makeAggName(input$dataset, date=TRUE)
  })

  output$GVis <- renderGvis({
#   gvisScatterChart(datasetInput())
     GPlots[[DTMadeName()]]
  })
  
  output$CInfo <- renderText({
#   hello world"
    if (is.null(input$CID))
        return ()
    outputCampaign(C.DT, as.character(input$CID))
  })

  output$InspectThese <- renderText({
      notUsing <- c("Gender", "Age")
      using <- setdiff(DTMadeName(), notUsing)

      if (!length(using))
           return(NULL)
      getExtremesInfo(using, qtls, howManyTopBot)
  })

  output$JSList <- reactive({
      paste0(js_before_terms,  
          paste0("\"", 
            removeNA(unique(
                DTs[[ DTMadeName() ]] [[ input$dataset ]]
             )),
            "\"", collapse=",\n" )   
        , js_after_terms )
  })
  
  output$JSUI <- renderUI({
    HTML(paste0( JS_pre,  


      paste0(js_before_terms,  
          paste0("\"", 
            removeNA(unique(
                DTs[[ DTMadeName() ]] [[ input$dataset ]]
             )),
            "\"", collapse=",\n" )   
        , js_after_terms )

      , JS_post))

  })

})

# runShiny("FBShiny_app")





# CID <- 6007006510053
# 
# CID <- as.character(CID)
# C.DT[.(CID)]
# 
# D <- C.DT[.(CID)]