---
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("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"))
#save(ca, file = "citizenair/data/ca.RData")

APPDATA <- ca
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"))
```


```{r}
popups <- list()
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)

## 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"))
      output$uiOutput_rawdata <- renderDT(datatable(APPDATA$getCitizenData("timeseries"), 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)
    }
  }
  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)
})
```

```{r}
## DEV APP SETTINGS
reactive <-  reactiveValues()
plots <- reactiveValues()
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("variable"=variables,summary)
reactive[["linear_model"]] <- linear_model
reactive[["regData"]]<- mydata
reactive[["summaryRaw"]] <- summary
```

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

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

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

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