# load libraries
library(nhdplusTools)
library(sf)

# set data dir
data_dir <- "data"
ifelse(
  !dir.exists(file.path(getwd(), paste0(data_dir, "/hydrologic"))),
  dir.create(file.path(getwd(), paste0(data_dir, "/hydrologic"), recursive = TRUE)), 
  FALSE)

nhdplusTools_data_dir(dir = paste0(data_dir, "/hydrologic"))

# load extent of map
extent <- read.csv(file = "extent.csv")
crs <- 4269

extent_poly <- st_polygon(
  x = list(
    cbind(
      extent$longitude[c(1,2,2,1,1)], 
      extent$latitude[c(1,1,2,2,1)])
  )
)

extent_poly <- st_sfc(extent_poly, crs=4326)
extent_bbox <- st_bbox(st_transform(x = extent_poly, crs))
extent <- list(longitude_max = max(extent$longitude),
               longitude_min = min(extent$longitude),
               latitude_max = max(extent$latitude),
               latitude_min = min(extent$latitude))

# get watershed areas
extent_huc <- get_huc(AOI = extent_poly, buffer = 0, type = "huc04")

# download data
download_nhdplushr(nhdplusTools_data_dir(), extent_huc$huc4, download_files = TRUE)

# get vaa
get_vaa()

# combine data into geopackage
layers <- c("NHDArea",
            "NHDFlowline",
            "NHDWaterbody",
            "NHDPlusLandSea")

data <- get_nhdplushr(hr_dir = nhdplusTools_data_dir(), 
                      out_gpkg = paste0(nhdplusTools_data_dir(),"/data.gpkg"),
                      layers = layers,
                      overwrite = TRUE)
