---
runtime: shiny
output: html_document
---

```{r, include = FALSE}
## Stop server when the web page is closed.
session <- getDefaultReactiveDomain()
session$onSessionEnded(function() shiny::stopApp())
```

```{r, include = FALSE}
## Globals

lausURL <- "http://www.stat.uiowa.edu/~luke/data/laus/laucntycur14-2018.txt"
lausUS <- read.table(lausURL,
                     col.names = c("LAUSAreaCode", "State", "County",
                                   "Title", "Period",
                                   "LaborForce", "Employed",
                                   "Unemployed", "UnempRate"),
                     quote = '', sep = "|", skip = 6,
                     stringsAsFactors = FALSE, strip.white = TRUE,
                     fill = TRUE)

footstart <- grep("------", lausUS$LAUSAreaCode)
lausUS <- lausUS[1:(footstart - 1),]

lausUS <- transform(lausUS,
                    UnempRate = as.numeric(UnempRate),
                    LaborForce = as.numeric(gsub(",", "", LaborForce)),
                    Employed = as.numeric(gsub(",", "", Employed)),
                    Unemployed = as.numeric(gsub(",", "", Unemployed)),
		    Period = substr(Period, 1, 6))

lausIA <- subset(lausUS, State == 19)

periods <- unique(lausIA$Period)
UI <- lapply(periods,
             function(p)
                 lausIA$UnempRate[lausIA$Period == p])

library(maps)
library(RColorBrewer)
palette <- brewer.pal(6, "Reds")


## Discreate version using map()

showMap <- function(p) {
    urate <- UI[[p]]
    levs <- cut(urate, seq(0, 10, by = 2))
    color <- palette[levs]
    map("county", "iowa", col = color, fill = TRUE)
    title(sprintf("Unemplotment Rates %s", periods[p]))
    legend("bottomleft", legend = levels(levs),
           fill = palette, cex = 0.6, bty = "n")
}


## Continuous version using ggplot
library(ggplot2)
library(dplyr)
giowa <- map_data("county", "iowa")
fips_idx <- match(paste(giowa$region, giowa$subregion, sep = ","),
                  sub(":,*", "", county.fips$polyname))
giowa$fips <- county.fips$fips[fips_idx]

lausIA <- transform(lausIA, fips = 1000 * State + County)

gUI <- as.data.frame(UI, col.names = periods)
gUI$fips <- lausIA$fips[lausIA$Period == periods[1]]
giowa_urate <- left_join(giowa, gUI)

mapthm <- theme_bw() %+replace% 
          theme(axis.line = element_blank(), axis.text = element_blank(), 
                axis.ticks = element_blank(), axis.title = element_blank(), 
                panel.background = element_blank(),
		panel.border = element_blank(), 
                panel.grid = element_blank(),
		panel.spacing = unit(0, "lines"),
		plot.background = element_blank())

gshowMap <- function(p) {
    per <- periods[p]
    cidx <- 7 + p
    rate <- giowa_urate[[cidx]]
    ggplot(giowa_urate, aes(long, lat, group = group)) +
    geom_polygon(aes(fill = rate), color = "grey") +
    scale_fill_distiller(palette = "Reds", direction = 1, limits = c(0, 10)) +
    coord_map() + mapthm + ggtitle(sprintf("Unemplotment Rates %s", per))
}

```

```{r echo = FALSE}
## Interface
radioButtons("type", "Ploy Type", c("map", "ggplot"))
sliderInput("period", "Period:", min = 1,  max = length(periods),
            value = 1, step = 1, animate = TRUE)

renderPlot(
    if (input$type == "map")
        showMap(input$period)
    else
        gshowMap(input$period))
```
