---
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

laus14file <- "laucntycur14-2025.xlsx"
if (! file.exists(laus14file)) {
    laus14URL <- paste0("http://www.stat.uiowa.edu/~luke/data/laus/",
                        laus14file)
    download.file(laus14URL, laus14file, mode = "wb")
}
lausUS <- readxl::read_xlsx(laus14file, skip = 2)
lausUS <- lausUS[1:(nrow(lausUS) - 2),]
names(lausUS) <-  c("LAUSAreaCode", "State", "County",
                    "Title", "Period",
                    "LaborForce", "Employed",
                    "Unemployed", "UnempRate")
lausUS$Period <- substr(lausUS$Period, 1, 6)

library(dplyr)

lausUS <- mutate(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 <- filter(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")


## Discrete 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)
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 <- mutate(lausIA, fips = 1000 * as.numeric(State) + as.numeric(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 = "black") +
    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", "Plot 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))
```
