## Sidebar {.sidebar}

#### Vergelijkingsbasis

```{r}
inputPanel(
radioButtons(inputId = "uiInput_periode", label = "Vergelijk op basis van", 
             choices = c("Per minuut" = "minute", "Per uur" = "hour", "Per dag" = "day", "Per maand" = "month", "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")
)
```

#### Vergelijk met ...

```{r}
actionBttn(inputId = "uiInput_selectstation", label = "Vergelijk met ander officieel station", style = "gradient")
```


## Verken je metingen {.tabset}

### Verken je metingen



```{r}
fillCol(
  tags$div("Hieronder tonen we een overzicht van jouw metingen en de dichtstbijzijnde VMM-meetplaats in
           functie van de tijd. 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, ga dan naar de volgende stap."),
  dygraphOutput("uiOutput_timeseries"),
  flex = c(NA, 1)
  )
output$uiOutput_timeseries <- renderDygraph({
  userdata <- citizenair_userdata()
  x <- userdata$appdata$getCitizenData("timeseries")
  if(nrow(x) > 0){
   x <- setDT(x)
   x$phenomena_label <- paste("Sheet ", x$sheet_id, ": ", x$phenomena, sep = "")
   ts <- dcast.data.table(data = x, formula = time ~ phenomena_label, fun.aggregate = mean, value.var = "value")
   ts <- setDF(ts)
   g <- xts(ts[, -1], order.by=ts[,1])
   g <- dygraph(g, main = "Tijdreeks van uw metingen")
   g <- dyRangeSelector(g, height = 20)
   g <- dyLegend(g, show = "always")
   ui <- g 
  }else{
    ui <- NULL
  }
  ui
})
observeEvent(input$uiInput_refresh, {
  output$uiOutput_timeseries <- renderDygraph({
  ## should depend on selected station
  id <- APPDATA$getComparisonStation()
  showNotification(sprintf("Getting data of station %s at the IRCEL web service", id))
  if(!is.na(id)){
    x <- APPDATA$fetch_timeseries(id)
    x <- setDT(x)
    ts <- dcast.data.table(data = x, formula = time ~ phenomena, fun.aggregate = mean, value.var = "value")
    ts <- setDF(ts)
    g <- xts(ts[, -1], order.by=ts[,1])
    g <- dygraph(g, main = sprintf("Tijdreeks van officieel meetstation %s", id))
    g <- dyRangeSelector(g, height = 20)
    g <- dyLegend(g, show = "always")
    g  
  }
})
})

```


### Selecteer een officieel meetstation om te vergelijken


```{r}
leafletOutput("uiOutput_select_station", width = "100%", height = 400)
output$uiOutput_select_station <- renderLeaflet({
  stations <- APPDATA$getStations()
  map <- leaflet(data = stations)
  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
})
```


### 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 me 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)
)

# Scatterplot of linear regression + CI & PI 
output$uiOutput_comparison <- renderPlot({
  req(c(reactive$regData,reactive$linear_model))
  mydata <- reactive$regData
  linear_model <- reactive$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
})
```

### Gevorderd overzicht van de vergelijking

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

```{r}
# outputs of dataframe & summaries
output$data <- renderTable({ 
  req(reactive[["regData"]])
  mydata <- reactive[["regData"]]
  avg.time <- "day"
  mydata <- timeAverage(mydata, avg.time=avg.time, data.thresh=85,statistic="mean")
  mydata$date <- as.character(as.POSIXct(mydata$date, origin="1970-01-01"))
  mydata})
output$summaryRaw <- renderTable({reactive[["summaryRaw"]]})
output$summaryValid <- renderTable({reactive[["summaryValid"]]})
```


## Inputs {data-width=150}


###

```{r}
renderValueBox({
  input$uiOutput_select_station_marker_click
  userdata <- citizenair_userdata()
  userdata$nearest_station <- userdata$appdata$getComparisonStation()
  stations <- userdata$appdata$getStations()
  stations <- subset(stations, id %in% userdata$nearest_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")  
  }else{
    ui <- NULL
  }
  ui
})
```


### 

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