# load libraries
library(sf)
library(tidyverse)
library(svglite)

# set dir to save figures to
figure_dir <- "figures"
ifelse(!dir.exists(file.path(getwd(), figure_dir)), dir.create(file.path(getwd(), figure_dir)), FALSE)

# set dimensions of figures
width <- 10
height <- 8
margin <- 0

# set state to highlight from political map
show_political <- FALSE
state <- c("Wisconsin")

# set lower threshold for displaying small lakes and streams
threshold_flowlines <- quantile(data$NHDFlowline$TotDASqKM, 0.80, na.rm = TRUE)
threshold_area <- quantile(data$NHDArea$AreaSqKM, 0.90, na.rm = TRUE)
threshold_waterbody <- quantile(data$NHDWaterbody$AreaSqKM, 0.90, na.rm = TRUE)

# plot map
plot_map <- function () {
  plot(sf::st_geometry(extent_poly), 
       col = NA,
       border = NA)
  plot(sf::st_geometry(political$geometry), 
       col = NA,
       border = "black",
       add = TRUE)
  if(show_political){
    plot(sf::st_geometry(political[political$NAME_En %in% state, ]), 
         col = NA,
         border = "black",
         add = TRUE)
  }
  plot(sf::st_geometry(data$NHDWaterbody %>% filter(AreaSqKM > threshold_waterbody)),
       col = "black",
       border = NA,
       add = TRUE)
  plot(sf::st_geometry(data$NHDArea %>% filter(AreaSqKM > threshold_area)),
       col = "black",
       border = NA,
       add = TRUE)
  plot(sf::st_geometry(data$NHDFlowline %>% filter(TotDASqKM > threshold_flowlines)),
       col = "black",
       lwd = (data$NHDFlowline %>% filter(TotDASqKM > threshold_flowlines) %>% pull(TotDASqKM))^0.43*0.0446,
       border = NA,
       add = TRUE)
  plot(sf::st_geometry(extent_poly),
       col = NA,
       border = "black",
       lwd = 1,
       add = TRUE)
}

## save figures
## generate tiff
svglite(filename = paste0(figure_dir,"/map.svg"),
        width = width,
        height = height)
par(mai=c(margin, margin, margin, margin))
par(mar=c(1,1,1,1))
plot_map()
dev.off()


