---
title: "Citizen Air - meet - evalueer - vergelijk"
runtime: shiny 
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    logo: img/logo-irceline-small.png
    theme: lumen 
---

```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(shinyWidgets)
library(data.table)
library(sensorweb4R)
library(httr)
library(readxl)
library(sp)
library(leaflet)
library(BelgiumMaps.StatBel)
library(rgeos)
library(citizenair)
library(DT)
library(sp)
library(xts)
library(dygraphs)
library(ggplot2)
library(openair)
data("BE_ADMIN_REGION", package = "BelgiumMaps.StatBel")
data("BE_ADMIN_BELGIUM", package = "BelgiumMaps.StatBel")
data("ca", package = "citizenair")

#ca <- CitizenAir$new(endpoint = as.Endpoint("http://geo.irceline.be/sos/api/v1"), stations_area = subset(BE_ADMIN_REGION, TX_RGN_DESCR_NL %in% "Vlaams Gewest"))
#ca <- CitizenAir$new(endpoint = as.Endpoint("http://geo.irceline.be/sos/api/v1"), stations_area = BE_ADMIN_BELGIUM)
#save(ca, file = "citizenair/data/ca.RData")

APPDATA <- ca
#APPDATA$setCitizenData(file = system.file(package = "citizenair", "data-raw", "citizenair-example.xls"))
#APPDATA$setComparisonStation(id = "1155")
#APPDATA <- CitizenAir$new(endpoint = as.Endpoint("http://geo.irceline.be/sos/api/v1"), 
#                          stations_area = subset(BE_ADMIN_REGION, TX_RGN_DESCR_NL %in% "Vlaams Gewest"))
APPDATA <- CitizenAir$new(endpoint = as.Endpoint("http://geo.irceline.be/sos/api/v1"), stations_area = BE_ADMIN_BELGIUM)
```

```{r}
plot_timeseries <- function(x, ...){
  if(nrow(x) > 0){
    x <- setDT(x)
    x$ts_id <- paste(x$type, x$phenomena, sep = "-")
    period_citizen <- x$time[x$type %in% "citizen"]
    if(length(period_citizen) > 0){
      #x <- subset(x, date >= (as.Date(min(period_citizen)) - 1) & date <= (as.Date(max(period_citizen)) + 1))  
    }
    ts <- dcast.data.table(data = x, formula = time ~ ts_id, fun.aggregate = mean, na.rm=TRUE, 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
}
```


```{r, eval=TRUE}
popups <- list()
popups$download <- modalDialog(title = "Download",
                               "We connecteren nu naar de IRCEL webservice om data af te halen en te combineren met uw meetgegevens, eventjes geduld, dit scherm sluit vanzelf wanneer dit afgelopen is.",
                               size = "s", footer = NULL, easyClose = FALSE)
popups$cleaned_data <- modalDialog(
  title = "Uw meetgegevens", 
  h4("Uw heeft de volgende gegevens opgeladen:"),
  tableOutput("uiOutput_rawmeta"),
  h4("Dit zijn de gegevens die we uit uw Excel file hebben gehaald: "),
  tags$hr(),
  DT::dataTableOutput("uiOutput_rawdata", width = "100%", height = "auto"),
  size = "l", footer = modalButton("Sluit"), easyClose = TRUE)
popups$select_station <- modalDialog(
  title = "Selecteer met welk officieel station u uw meetgegevens wilt vergelijken",
  tags$div(tags$blockquote("Op de kaart hieronder kunt u meetstations vinden van de Vlaamse Milieu Maatschappij die dezelfde elementen meten als uw metingen. Selecteer het meetstation waarmee u uw eigen gegevens wil vergelijken door te klikken op een meetstation. Wanneer u klaar bent, klik op Go!, waarna we de gegevens van de VMM webservice afhalen en combineren met uw gegevens.")),
  renderUI(tags$h3("Uw selecteerde te vergelijken met: ", citizenair_vmmstation()$label)),
  radioGroupButtons(
        inputId = "uiInput_selectmeasurement", 
        label = "Selecteer welke van uw sensorgegevens u wilt vergelijken met een officieel meetstation", 
        choices = sort(APPDATA$getCitizenData(type = "phenomena"), decreasing = TRUE),
        #choices = LETTERS, 
        direction = "horizontal", size = "sm",
        justified = FALSE, individual = FALSE, status = "primary",
        checkIcon = list(yes = icon("ok", lib = "glyphicon"))
      ),
  actionButton(inputId = "uiInput_downloadtimeseries", 
               label = "Go! Haal de meetgegevens af vanaf de VMM webservice en start de vergelijking",
               "data-dismiss"="modal", 
               icon = icon("arrow-circle-down")),
  tags$hr(),
  leafletOutput("uiOutput_select_station", width = "100%", height = 300),
  size = "l", footer = NULL, easyClose = FALSE)


citizenair_vmmstation <- reactive({
  input$uiOutput_select_station_marker_click
  id <- input$uiOutput_select_station_marker_click$id
  list(id = id, label = APPDATA$getStationLabel(id))
})


## MAIN REACTIVE WHICH LOADS THE EXCEL FILE
citizenair_userdata <- reactive({
  input$uiInput_xl
  result <- list()
  result$appdata <- APPDATA
  result$nearest_station <- result$appdata$getClosestStation()
  if(!is.null(input$uiInput_xl)){
    showNotification("We lezen uw Excel bestand in wacht even...", duration = 5)
    x <- try(result$appdata$setCitizenData(file = input$uiInput_xl$datapath, name = input$uiInput_xl$name))
    if(inherits(x, "try-error")){
      showNotification(sprintf("Er loopt iets fout, is uw data bestand wel een correct bestand? %s", error_message(x)), 
                       type = "error", duration = 15)
    }else{
      result$nearest_station <- result$appdata$getClosestStation()
      APPDATA$setComparisonStation(result$nearest_station)
      output$uiOutput_rawmeta <- renderTable(APPDATA$getCitizenData("meta"))
      x <- APPDATA$getCitizenData("timeseries")
      APPDATA$setCombinedTimeseries(x)
      x$sheet <- x$timeseries_label
      x <- x[, c("sheet", "phenomena", "time", "value")]
      output$uiOutput_rawdata <- renderDT(datatable(x, rownames = FALSE, 
                                                    caption = 'Overzicht van alle meetgegevens per sheet/tijdstip/type meting', 
                                                    filter = 'top', options = list(pageLength = 5, autoWidth = TRUE, searching = FALSE)))  
      showModal(popups$cleaned_data)
      
      output$uiOutput_timeseries <- renderDygraph({
        plot_timeseries(result$appdata$getCombinedTimeseries(), main = "De tijdreeks van al uw meetgegevens")
      })
    }
  }
  result
})
reactive({
  ## On click on the station selection leaflet user interface, change the comparison station
  input$uiOutput_select_station_marker_click
  APPDATA$setComparisonStation(input$uiOutput_select_station_marker_click$id)
})
```

# Data {data-icon="fa-cloud-upload"}

```{r child="page01-introduction.Rmd", eval=FALSE}
```

# Exploreer en vergelijk {data-icon="fa-toggle-on"}

```{r child="page02-exploratory.Rmd", eval=FALSE}
```

# Hidden 

## Main event

```{r}
## Main trigger for updating graphs
numericInput(inputId = 'uiInput_refresh_counter', label = "How many updates are done", value = 0)
```

## Debugging

```{r}
tags$h3("Input")
renderPrint({
  names(input)
})
tags$h3("Output")
renderPrint({
  names(output)
})
tags$h3("session")
renderPrint({
  names(session)
})
```

