#! /usr/bin/Rscript
library(shiny)
library(leaflet)
library(dplyr)
library(shinyWidgets)
library(htmltools)
library(rgdal)
library(rgeos)
library(ggfortify)

leafcols <- c("blue", "red", "darkred", "lightred",
          "orange", "beige", "green", "darkgreen",
          "lightgreen", "darkblue", "lightblue",
          "purple", "darkpurple", "pink", "cadetblue",
          "white", "gray", "lightgray", "black", "pink", "cyan")

Geo2017 <- readRDS("Geo2017.rds")
Geo2017$Snargle <- c(TRUE, rep(FALSE, 5))

DHBs <- sort(unique(Geo2017$dhb_name))
DHBs <- c(DHBs[DHBs != "Missing"], "Missing")

# dhbcols <- leafcols[1:length(DHBs)]
dhbcols <- hcl.colors(length(DHBs))
names(dhbcols) <- DHBs
dhbcol <- function(DHB) {
    sdf <- dhbcols[DHB]
    names(sdf) <- NULL
    sdf
}
snargcols <- leafcols[1:2]
names(snargcols) <- c(FALSE, TRUE)
snargcol <- function(snarg) {
    sdf <- snargcols[as.character(snarg)]
    names(sdf) <- NULL
    sdf
}

dhb2015 <- readRDS("dhb2015.rds")

popups <- function(data) {
sprintf("<strong>%s</strong><br/>%s<br/>DHB: %s<br/>%s",
        htmlEscape(data$name),
        htmlEscape(data$address),
        htmlEscape(ifelse(data$dhb_name == "Missing",
                          "None", data$dhb_name)),
        ifelse(data$Snargle,
               "Snargleflagen practice",
               "Non-snargleflagen practice"))
}


ui <- fillPage(title = "New Zealand GP Practice Locations 2017",
    tags$style(type = "text/css", 
               "#medmap {
                 height: 100% !important;
                 /*posiiton: absolute;*/
                 top: 0;
                 left: 0;
               }
               .dropdowncont {
                 position: fixed;
                 top: 0;
                 right: 0;
                 z-index: 10;
               }
               .dropdowncont ul {
                 overflow-y: auto;
                 max-height: calc(100vh - 100px);
               }"),
    div(class = "dropdowncont",
    dropdownButton(
      strong("Not Implemented"), hr(),
      searchInput("mapsearch",
                  placeholder = "Search GP practices by name",
                  btnSearch = icon("search"), 
                  btnReset = icon("remove"), 
                  width = "100%"),
      hr(),
      radioButtons("selcol", "Colour by",
                   choices = c("None" = "None",
                               "DHB affiliation" = "DHB",
                               "Snargleflagen" = "Snargleflagen")),
      hr(),
      checkboxInput("dhboverlay", "Show DHB boundaries"),
      hr(),
      actionLink("closedrop", label = "close", icon = icon("close"),
                 style="float:right"),
      circle=FALSE, inputId = "ddown", right = TRUE,
      label = "Options", inline = FALSE, icon = icon("gear"), status = "danger")),
    leafletOutput(outputId = "medmap")
)


server <- function(input, output, session) {
    output$medmap <- renderLeaflet({
        gl <- leaflet(Geo2017) %>%
          addMapPane("polygons", zIndex = 420) %>%
          addMapPane("markers", zIndex = 430)
        gl <- addTiles(gl)
        gl <- addCircleMarkers(gl, lng = Geo2017$lon,
                   lat = Geo2017$lat,
                   popup = popups(Geo2017),
                   col= "blue",
                   #pathOptions(pane = "markers")
                   )
        gl
    })

    observeEvent(input$closedrop, {
      toggleDropdownButton("ddown")
    })

    observeEvent(input$selcol, {
      gl <- leafletProxy("medmap") %>%
          clearMarkers()
      if (input$selcol == "Snargleflagen") {
          gl <- addCircleMarkers(gl, lng = Geo2017$lon,
                     lat = Geo2017$lat,
                     popup = popups(Geo2017),
                     # color = snargcols[as.character(Geo2017$dhb_name)]
                     col = snargcol(Geo2017$Snargle),
                     #pathOptions(pane = "markers")
                     )
      } else if (input$selcol == "DHB") {
          gl <- addCircleMarkers(gl, lng = Geo2017$lon,
                     lat = Geo2017$lat,
                     popup = popups(Geo2017),
                     # color = dhbcols[Geo2017$dhb_name]
                     col = dhbcol(Geo2017$dhb_name),
                     #pathOptions(pane = "markers")
                     )
      } else {
          gl <- addCircleMarkers(gl, lng = Geo2017$lon,
                     lat = Geo2017$lat,
                     popup = popups(Geo2017),
                     col= "blue",
                     #pathOptions(pane = "markers")
                     )
      }
    })

    observeEvent(input$mapsearch, {
      ms <- input$mapsearch
      if (ms != "") {
        dists <- as.vector(adist(ms, Geo2017$name, 
                                 costs = c("in" = 1, "del" = 1, "sub" = 1), 
                                 fixed = TRUE,
                                 partial = TRUE,
                                 ignore.case = TRUE))
        md <- which.min(dists)
        updateSearchInput(session, inputId = "mapsearch", value = Geo2017$name[md])
        leafletProxy("medmap") %>% setView(lng = Geo2017$lon[md],
                                         lat = Geo2017$lat[md],
                                         zoom = 13)
      }
    })
    observeEvent(input$dhboverlay, {
      if (input$dhboverlay) {
        leafletProxy("medmap") %>% addPolygons(data = dhbsub, fill = FALSE,
                                               color = "#000000",
                                               weight = 2,
                                               #pathOptions(pane = "polygons")
                                               )
      } else {
        leafletProxy("medmap") %>% clearShapes()
      }
    })

}

# Run the application 
shinyApp(ui = ui, server = server)
