library(dplyr)
library(rlang)
library(purrr)
library(here)
library(fs)
library(glue)
library(sf)
library(ggplot2)
library(plotly)
library(scales)
library(mapview)
library(DT)
library(rerddap)
library(lubridate)
library(readr)
library(stringr)
here = here::here

q_calcofi        <- "CalCOFI Larvae Counts, Scientific Names"
dir_cache        <- here("cache") 
dir_img          <- "/Volumes/GoogleDrive/My Drive/projects/nms-web/cinms/Images"
lrvcntSBtoSC_csv <- glue("{dir_cache}/erdCalCOFIlrvcntSBtoSC.csv")
stns_cinms_csv   <- here("data/stns_cinms.csv")
plys_cinms_geo   <- here("data/plys_cinms.geojson")
yr_min           <- 1978
spp_csv          <- here("data/spp.csv")
spp_grps_csv     <- here("data/spp_grps.csv")
redo_grp_ply_csv <- F

# functions ----
convert_fig <- function(fig_beg, fig_end, redo=F){
  stopifnot(file.exists(fig_beg), dir.exists(dirname(fig_end)))
  #browser()
  if (!file.exists(fig_end) | redo){
    cmd <- glue("magick convert '{fig_beg}' -resize 800 -alpha on '{fig_end}'")
    system(cmd)
    
    paths_01 <- glue("{path_ext_remove(fig_end)}-{c(0,1)}.png")
    if (all(file.exists(paths_01))){
      file_copy(paths_01[2], fig_end, overwrite = T)
      file_delete(paths_01)
    }
  }
}  

get_nms_ply <- function(nms){
  # eg get_nms_ply("cinms")
  # get polygon for National Marine Sanctuary
  
  nms_shp <- here(glue("data/shp/{nms}_py.shp"))
  
  if (!file.exists(nms_shp)){
    # download if needed
    
    # https://sanctuaries.noaa.gov/library/imast_gis.html
    nms_url <- glue("https://sanctuaries.noaa.gov/library/imast/{nms}_py2.zip")
    nms_zip <- here(glue("data/{nms}.zip"))
    shp_dir <- here("data/shp")
    
    download.file(nms_url, nms_zip)
    unzip(nms_zip, exdir = shp_dir)
    file_delete(nms_zip)
  }
  # read and convert to standard geographic projection
  read_sf(nms_shp) %>%
    st_transform(4326)
}

Reference CINMS Condition Report figures

App.F.12.17 map of net samples

figs <- list(
  folder = "App F: LR (AppF.Q#.#)/AppendixF_Q12",
  figure = c(
    "App.F.12.17.Map_CalCOFI.tiff"))

figs_beg <- path(dir_img, figs$folder, figs$figure)
figs_end <- here(glue("docs/figures/{path_ext_remove(basename(figs_beg))}.png"))
walk2(figs_beg, figs_end, convert_fig)
knitr::include_graphics(figs_end)