## Sidebar {.sidebar}

#### Selecteer meetwaardes

```{r}
renderUI({
    userdata <- citizenair_userdata()
    polluent_id <- userdata$appdata$getPhenomena("citizen")
    polluent_label <- userdata$appdata$getPhenomenaLabel(polluent_id)
    if(length(polluent_id) > 0){
      choices <- structure(as.list(polluent_id), .Names = polluent_label)
      ui <- checkboxGroupButtons(inputId = "uiInput_phenomena", #label = "Selecteer meetwaardes", 
                                 choices = choices, selected = choices, 
                                 direction = "vertical", size = "sm", justified = FALSE, individual = FALSE, status = "primary", 
                                 checkIcon = list(#no = icon("remove", lib = "glyphicon", 
                                   yes = icon("ok", lib = "glyphicon")))
      #ui <- selectInput(inputId = "uiInput_phenomena", label = NULL, choices = choices, selected = choices, multiple = TRUE)
    }else{
      ui <- NULL
    }
    ui
  })
tags$hr()
```

#### Vergelijk met officieel meetstation

```{r}
actionBttn(inputId = "uiInput_selectstation", label = "Haal data op van een officieel station", style = "gradient")
tags$hr()
## Show input to select the station
observeEvent(input$uiInput_selectstation, {
  userdata <- citizenair_userdata()
  showModal(popups$select_station)  
  choices <- sort(userdata$appdata$getCitizenData(type = "phenomena"), decreasing = TRUE)
  if(length(choices) > 0){
    #Match citizen phenomena (choices) to ircel phenomena
    choices_ircel <- userdata$appdata$recode_phenomena(choices)
    choices_ircel <- userdata$appdata$getPhenomenaLabel(choices_ircel)
    #User interface input selects ircel identifiers, get the IRCEL labels
    selection <- userdata$appdata$getPhenomenaLabel(input$uiInput_phenomena)
    selection <- head(selection, 1)
    selection <- which(choices_ircel %in% selection)
    selection <- head(selection, 1)
    if(length(selection) > 0){
      updateRadioGroupButtons(session, inputId = "uiInput_selectmeasurement", 
                            choices = choices, selected = choices[selection], 
                            size = "sm", status = "primary", checkIcon = list(yes = icon("ok", lib = "glyphicon")))  
    }else{
      updateRadioGroupButtons(session, inputId = "uiInput_selectmeasurement", 
                              choices = choices, 
                              size = "sm", status = "primary", checkIcon = list(yes = icon("ok", lib = "glyphicon")))  
    }
    
  }
  output$uiOutput_select_station <- renderLeaflet({
    input$uiInput_selectmeasurement
    stations <- APPDATA$getStations()
    official_measurements <- APPDATA$recode_phenomena(input$uiInput_selectmeasurement)
    stations <- stations[sapply(stations$phenomena, FUN=function(x) any(x %in% official_measurements)), ]
    if(nrow(stations) == 0){
      showNotification("We vonden geen meetstations voor uw selectie")
    }
    map <- leaflet(data = stations)
    map <- addControl(map, html = input$uiInput_selectmeasurement, position = "topleft")
    map <- addTiles(map)
    map <- addCircleMarkers(map = map, data = stations, radius = 5, opacity = 0.3, fillOpacity = 1, weight = 3, 
                            layerId = stations$id,
                            popup = as.character(mapply(id = stations$id, label = stations$label, phenomena = stations$phenomena_label, 
                                                        FUN=function(id, label, phenomena){
                                                          sprintf("<b>Station %s: %s</b> <br>Meetwaardes:<br> %s", id, label, paste(sprintf(" - %s ", phenomena), collapse = "<br>"))
                                                        })))
    map
  })
})
## MAIN REACTIVE WHICH COMBINES CITIZEN DATA + OFFICIAL DATA -- USES THE POPUP
observeEvent(input$uiInput_downloadtimeseries, {
  result <- list()
  result$userdata <- citizenair_userdata()
  citizen <- result$userdata$appdata$getCitizenData("timeseries")
  result$station <- result$userdata$appdata$getComparisonStation()
  period <- lubridate::as.interval(as.POSIXct(input$uiInput_period[1] - 1), as.POSIXct(input$uiInput_period[1] + 1))
  if(length(result$station) > 0){
    showModal(popups$download)
    showNotification(sprintf("We halen nu data af vanaf de IRCEL webservice van meetstation %s %s", result$station, result$userdata$appdata$getStationLabel(result$station)))
  }
  #official <- try(result$userdata$appdata$fetch_timeseries(result$station, time_span = period))
  official <- try(result$userdata$appdata$fetch_timeseries(result$station))
  removeModal()
  if(inherits(official, "try-error")){
      showNotification(sprintf("Er loopt iets fout met het ophalen van de data vanaf de IRCEL webservice: %s", error_message(official)), 
                       type = "error", duration = 15)
      official <- result$userdata$appdata$fetch_timeseries(NULL)
  }else{
    if(nrow(official) > 0){
      showNotification("Data werd afgehaald vanaf de IRCEL webservice en werd gecombineerd met uw meetgegevens", type = "message")    
    }
  }
  result$data <- list()
  result$data$citizen <- citizen
  result$data$official <- official
  result$data <- rbindlist(result$data, use.names = TRUE)
  APPDATA$setCombinedTimeseries(result$data)
  
  updateNumericInput(session, inputId = 'uiInput_refresh_counter', value = input$uiInput_refresh_counter + 1)

  #x <- APPDATA$getCombinedTimeseries(type = "rawdata", limit = TRUE)
  #x <- subset(x, phenomena_id %in% input$uiInput_phenomena)
  #output$uiOutput_timeseries <- renderDygraph(plot_timeseries(x, main = "De tijdreeks van al uw meetgegevens samen met de gegevens van de Vlaamse Milieu Maatschappij"))
})
```


#### Vergelijkingsbasis

```{r}
#inputPanel(
  radioButtons(inputId = "uiInput_aggregationlevel", label = "Vergelijk", 
               choices = c("Per minuut" = "min", 
                           "Per uur" = "hour", 
                           "Per dag" = "day", 
                           "Per maand" = "month", 
                           "Op basis van ruwe data" = "rawdata"), 
               selected = "rawdata")
  dateRangeInput(inputId = "uiInput_period", label = "Verander de periode", start = Sys.Date()-365, end = Sys.Date())
  #actionButton(inputId = "uiInput_refresh", label = "Herbereken grafiek")
#)
observe({
  userdata <- citizenair_userdata()
  timerange <- userdata$appdata$getCitizenData("timerange")
  if(timerange$valid){
    updateDateRangeInput(session, inputId = "uiInput_period", start = as.Date(timerange$start), end = as.Date(timerange$end))  
  }
})

```

```{r}
#observeEvent(input$uiInput_refresh, {
#  updateNumericInput(session, inputId = 'uiInput_refresh_counter', value = input$uiInput_refresh_counter + 1)
#})
reactive({
  input$uiInput_refresh_counter
  input$uiInput_phenomena
  input$uiInput_aggregationlevel
  input$uiInput_sheet
  input$uiInput_period 
  x <- APPDATA$getCombinedTimeseries(type = "rawdata")
  x <- subset(x, type %in% "official" | (type %in% "citizen" & timeseries_id %in% input$uiInput_sheet))
  x <- subset(x, phenomena_id %in% input$uiInput_phenomena)
  x <- x[as.Date(x$time) >= (as.Date(input$uiInput_period[1])) & as.Date(x$time) <= (as.Date(input$uiInput_period[2])), ]
  x <- APPDATA$getCombinedTimeseries(x, type = input$uiInput_aggregationlevel, limit = TRUE)
  output$uiOutput_timeseries <- renderDygraph(plot_timeseries(x))
})
    

  
reactive({
  input$uiInput_refresh_counter
  input$uiInput_phenomena
  input$uiInput_aggregationlevel
  input$uiInput_sheet
  input$uiInput_period
  
  #showNotification("Herberekening wordt uitgevoerd")
  #input$uiInput_phenomena
  #input$uiInput_aggregationlevel
  #input$uiInput_sheet
  #input$uiInput_period 
  #input$uiOutput_select_station_marker_click
  x <- APPDATA$getCombinedTimeseries(type = "rawdata")
  x <- subset(x, type %in% "official" | (type %in% "citizen" & timeseries_id %in% input$uiInput_sheet))
  x <- subset(x, phenomena_id %in% input$uiInput_phenomena)
  x <- x[as.Date(x$time) >= (as.Date(input$uiInput_period[1])) & as.Date(x$time) <= (as.Date(input$uiInput_period[2])), ]
  x <- APPDATA$getCombinedTimeseries(x, type = input$uiInput_aggregationlevel, limit = TRUE)
  #output$uiOutput_timeseries <- renderDygraph(plot_timeseries(x))
  
  try({
  mydata <- subset(x, phenomena_id %in% head(input$uiInput_phenomena, 1))
  if(all(c("citizen", "official") %in% mydata$type) & input$uiInput_aggregationlevel %in% c("min", "hour", "day", "week", "month")){
    ## DATE/REF/SENSOR
    mydata <- x
    mydata$group <- ifelse(mydata$type %in% "official", "REF", "SENSOR")
    mydata$date <- mydata$time
    mydata <- dcast.data.table(data = mydata, formula = date ~ group, fun.aggregate = mean, na.rm=TRUE, value.var = "value")
    #mydata <- data.frame(date = as.POSIXct(seq.Date(Sys.Date(), Sys.Date()-999, by = "-1 day"), tz = "UTC"), 
    #                     REF = rnorm(1000), 
    #                     SENSOR = rnorm(1000))
    linear_model <- lm(mydata$SENSOR ~ mydata$REF)
    PI <- data.frame(predict(linear_model, interval="predict", level = 0.95))
    colnames(PI) <- c("OLSQ", "lower PI", "upper PI")
    CI <- data.frame(predict(linear_model, interval="confidence", level = 0.95))
    colnames(CI) <- c("OLSQ", "lower CI", "upper CI")
    mydata <- cbind(mydata, "OLSQ" = CI$OLSQ,
                    "lower_CI" = CI$`lower CI`, 
                    "upper_CI"=CI$`upper CI`, 
                    "lower_PI" = PI$`lower PI`, 
                    "upper_PI" = PI$`upper PI`)
    mydata$e <- mydata$OLSQ - mydata$SENSOR
    mydata <- mydata[order(mydata[,1]), ]
    summary <- data.frame(do.call(cbind, lapply(mydata, summary)))[-7,]
    summary$date <- as.character(as.POSIXct(summary$date, origin="1970-01-01"))
    summary <- rbind(summary,"# Valid"=colSums(!is.na(mydata)))
    summary <- rbind(summary,"# NA's"=colSums(is.na(mydata)))
    variables <- c("min", "25th Perc", "median", "mean","75th Perc", "max","# Valid", "# NA's")
    summary <- cbind("statistiek"=variables,summary)
    
    # outputs of dataframe & summaries
    output$data <- renderTable({ 
      mydata <- timeAverage(mydata, avg.time=input$uiInput_aggregationlevel, data.thresh=85, statistic="mean")
      mydata$date <- as.character(as.POSIXct(mydata$date, origin="1970-01-01"))
      mydata
    })
    output$summaryRaw <- renderTable(summary)
    # Scatterplot of linear regression + CI & PI 
    output$uiOutput_comparison <- renderPlot({
      mydata <- mydata
      linear_model <- linear_model
      plot_PI_CI <- ggplot(data = mydata, aes(x = REF, y = SENSOR)) + 
        geom_ribbon(aes(ymin = lower_CI, ymax=upper_CI, fill = "CI"),alpha = 0.6) +
        geom_ribbon(aes(ymin = lower_PI, ymax=upper_PI, fill = "PI"), alpha = 0.4) +
        geom_point() +
        geom_line(aes(y = OLSQ,col = "OLSQ")) +
        geom_line(aes(y = REF,col = "y=x")) +
        labs(title = paste("Scatterplot with regression estimates: intercept =",
                           format(summary(linear_model)$coefficients[1,1], digits = 3),
                           ",slope =",format(summary(linear_model)$coefficients[2,1], digits = 3),
                           ",R² =",format(summary(linear_model)$r.squared, digits = 3)),
             x = "Reference value",
             y = "Sensor") +
        scale_fill_manual(name="",values=c("CI"="blue","PI"= "grey")) +
        scale_colour_manual(name="", values = c("y=x"="red","OLSQ"="black"))
      #plots[["scatter"]] <- plot_PI_CI
      plot_PI_CI
    })
  }  
  })
})
```


## Verken je metingen {.tabset}

### Verken je metingen

```{r}
fillCol(
  tags$div("Hieronder tonen we een overzicht van jouw metingen. Verken je meting hieronder en kijk eens wat er gebeurt als je uitmiddelt per uur, per dag enz. Als je een goed zicht hebt op je data, haal dan data op van een officieel meetstation om uw metingen mee te vergelijken."),
  dygraphOutput("uiOutput_timeseries"),
  flex = c(NA, 1)
)
```


### Meet mijn meettoestel zoals een officieel toestel


```{r}
fillCol(
  tags$div(
      tags$h4("De Vlaamse Milieu Maatschappij heeft meetresultaten die aan de strengste kwaliteitseisen voldoen. Hieronder tonen
we een eenvoudige statistische vergelijking tussen onze meetgegevens en die van jouw. Verander ook de VMM-meetplaats eens, een andere meetplaats komt misschien beter met de jouwe overeen!"),
      tags$h5("Onderstaande grafiek toont alle meetwaardes van uw toestel uitgezet tov alle meetwaardes van een toestel van de Vlaamse Milieu Maatschappij")),
  fillRow(dropdownButton(
    tags$h3("Selectie dagen van de week"),
    radioButtons(inputId = "uiInput_dayofweek", label = "Vergelijk op basis van", 
             choices = c("Alle dagen van de week" = "all", "Enkel weekdagen" = "weekdays", "Enkel weekend" = "weekend"), 
             selected = "all"),
    #tags$h3("Input voor de grafiek"),
    #sliderInput(inputId = "uiInput_slider", label = "TODO", value = 25, min = 5, max = 100, step = 1L, round = TRUE),
    circle = TRUE, status = "info", icon = icon("gear"), width = "300px", size = "sm",
    tooltip = tooltipOptions(title = "Verdere opties")),
    plotOutput("uiOutput_comparison", height = "100%"),
    flex = c(NA, 2)
  ),
  flex = c(NA, 2)
)
```

### Gevorderd overzicht van de vergelijking

```{r}
fillCol(
  tableOutput("summaryRaw"),
  tags$hr(),
  tableOutput("data"),
  flex = c(NA, NA, 1)
)
```




## Inputs {data-width=150}


###

```{r}
renderValueBox({
  ## Triggers each time a user clicks on the leaflet app or when a user uploads new data
  userdata <- citizenair_userdata()
  comparison_station <- input$uiOutput_select_station_marker_click
  if(length(comparison_station) == 0){
    comparison_station <- userdata$nearest_station
  }
  ui <- NULL
  if(length(comparison_station) > 0){
    stations <- userdata$appdata$getStations()
    stations <- subset(stations, id %in% comparison_station)
    if(nrow(stations) > 0){
      txt <- stations$label
      txt <- strsplit(txt, "-")[[1]]
      txt <- trimws(txt)
      txt <- HTML(paste(txt, collapse = "<br>"))
      ui <- valueBox(txt, caption = "Vergelijk met officieel meetstation")  
    }
  }
  ui
})
```

### 

```{r}
renderValueBox({
  userdata <- citizenair_userdata()
  filename <- userdata$appdata$getCitizenData("fileinfo")$name
  if(length(filename) > 0){
    ui <- valueBox("Uw excel file", caption = filename)    
  }else{
    ui <- NULL 
  }
  ui
})
```

### 

```{r}
renderUI({
  userdata <- citizenair_userdata()
  x <- userdata$appdata$getCitizenData("meta")
  if(is.data.frame(x) && nrow(x) > 0){
    choices <- structure(as.list(x$sheet_id), .Names = x$sheet)
    ui <- selectInput(inputId = "uiInput_sheet", label = "Selecteer sheet", choices = choices, selected = choices, multiple = TRUE)
  }else{
    ui <- NULL
  }
  ui
})
```
