## Sidebar {.sidebar}

```{r}
plot_timeseries <- function(x){
  if(nrow(x) > 0){
    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)
    g <- dyRangeSelector(g, height = 20)
    g <- dyLegend(g, show = "always")
    g  
  }else{
    g <- NULL
  }
  g
}
# isolate({
#     input$uiInput_aggregationlevel
#     input$uiInput_sheet
#     input$uiInput_period 
#     input$uiOutput_select_station_marker_click
#   })
```

#### Vergelijk met ...

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

#### Vergelijkingsbasis

```{r}
inputPanel(
radioButtons(inputId = "uiInput_aggregationlevel", label = "Vergelijk", 
             choices = c("Per minuut" = "minute", "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")
)
```

```{r}
## MAIN REACTIVE WHICH COMBINES CITIZEN DATA + OFFICIAL DATA
observeEvent(input$uiInput_refresh, {
  result <- list()
  result$userdata <- citizenair_userdata()
  citizen <- result$userdata$appdata$getCitizenData("timeseries")
  result$station <- result$userdata$appdata$getComparisonStation()
  if(length(result$station) > 0){
    showNotification("Haalt data af vanaf de IRCEL webservice")
  }
  official <- try(result$userdata$appdata$fetch_timeseries(result$station))
  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)
  output$uiOutput_timeseries <- renderDygraph(plot_timeseries(result$data))
})
```


## 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({
  ## Default call when user only uploaded his own data
  userdata <- citizenair_userdata()
  x <- userdata$appdata$getCombinedTimeseries()
  plot_timeseries(x)
})
```


### 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({
  ## Triggers each time a user clicks on the leaflet app or when a user uploads new data
  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
})
```
