#' Download and plot essential climate data
#'
#' Retrieves atmospheric carbon dioxide measurements from National Oceanic and Atmospheric Administration
#' Earth System Research Laboratories monitoring laboratory in Mauna Loa, Hawaii.
#' \url{https://gml.noaa.gov/ccgg/trends/data.html}
#'
#' @name get_carbon
#' @param use_cache (boolean) Return cached data if available, defaults to TRUE. Use FALSE to fetch updated data.
#' @param write_cache (boolean) Write data to cache, defaults to FALSE. Use TRUE to write data to cache for later use. Can also be set using options(hs_write_cache=TRUE)
#'
#' @return Invisibly returns a tibble with the monthly carbon dioxide series
#'
#' @details `get_carbon` invisibly returns a tibble with NOAA's monthly average carbon dioxide measurement.
#' The returned object includes date, year, month, average, trend, std dev, and uncertainty columns.
#' Trend is NOAA's published trend.  Please refer to above website for details.
#'
#' @importFrom readr read_table
#' @importFrom lubridate ymd ceiling_date
#' @importFrom utils download.file
#'
#' @examples
#' \donttest{
#' # Fetch from cache if available, otherwise download:
#' maunaloa <- get_carbon()
#' #
#' # Force fetch from source:
#' maunaloa <- get_carbon(use_cache=FALSE)
#' #
#' # Review cache contents and last update dates:
#' hockeystick_cache_details()
#' #
#' # Plot output using package's built-in ggplot2 settings
#' plot_carbon(maunaloa) }
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#' @references
#' Dr. Pieter Tans, NOAA/GML \url{https://gml.noaa.gov/ccgg/trends/} and Dr. Ralph Keeling, Scripps Institution of Oceanography \url{https://scrippsco2.ucsd.edu/}.
#'
#'
#' C.D. Keeling, R.B. Bacastow, A.E. Bainbridge, C.A. Ekdahl, P.R. Guenther, and L.S. Waterman, (1976), Atmospheric carbon dioxide variations at Mauna Loa Observatory, Hawaii, \emph{Tellus}, vol. 28, 538-551
#' @export
get_carbon <- function(use_cache = TRUE, write_cache = getOption("hs_write_cache")) {

hs_path <- tools::R_user_dir("hockeystick","cache")

if (use_cache & !write_cache) {
  if (file.exists(file.path(hs_path,'maunaloa.rds'))) return(invisible(readRDS((file.path(hs_path,'maunaloa.rds')))))
  }

file_url <- 'https://gml.noaa.gov/webdata/ccgg/trends/co2/co2_mm_mlo.csv'
connected <- .isConnected(file_url)
if (!connected) {message("Retrieving remote data requires connectivity to source."); return(invisible(NULL))}

dl <- tempfile()
status <- tryCatch(suppressWarnings(download.file(file_url, dl)), error = function(e) 1L)
if (status!=0L) {message("Unable to access remote resource."); return(invisible(NULL))}

maunaloa <- suppressMessages( read_csv(dl, col_names = FALSE, skip = 41) )
colnames(maunaloa) <- c('year', 'month', 'date', 'average', 'trend', 'ndays','stdev','unc')
maunaloa$date <- ceiling_date(ymd(paste(maunaloa$year, maunaloa$month, '01',sep='-')), unit='month')-1

dir.create(hs_path, showWarnings = FALSE, recursive = TRUE)
if (write_cache) saveRDS(maunaloa, file.path(hs_path, 'maunaloa.rds'))

invisible(maunaloa)
}



#' Download and plot essential climate data
#'
#' Plots carbon dioxide data retrieved using `get_carbon()` with ggplot2. The output ggplot2 object may be modified.
#'
#'
#' @name plot_carbon
#' @param dataset Name of the tibble generated by `get_carbon`
#' @param print (boolean) Display carbon dioxide ggplot2 chart, defaults to TRUE. Use FALSE to not display chart.
#' @param annot (boolean) Include chart annotation with latest date and value, defaults to TRUE.
#'
#' @return Invisibly returns a ggplot2 object with carbon dioxide chart
#'
#' @details `plot_carbon` invisibly returns a ggplot2 object with a pre-defined carbon dioxide chart using data from `get_carbon`.
#' By default the chart is also displayed. Users may further modify the output ggplot2 chart.
#'
#' @import ggplot2
#' @importFrom dplyr pull slice
#'
#' @examples
#' \donttest{
#' # Fetch carbon dioxide data:
#' maunaloa <- get_carbon()
#' #
#' # Plot output using package's built-in ggplot2 defaults
#' plot_carbon(maunaloa)
#'
#' # Or just call plot_carbon(), which defaults to get_carbon() dataset
#' plot_carbon()
#'
#' p <- plot_carbon(maunaloa, print = FALSE)
#' # Modify plot such as: p + ggplot2::labs(title='The Keeling Curve') }
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#'
#' @export

plot_carbon <- function(dataset = get_carbon(),
                        print = TRUE, annot = TRUE) {

if (is.null(dataset)) return(invisible(NULL))

plot <- ggplot(dataset, aes(x=date, y=average)) +geom_line(color='dodgerblue2', alpha=0.7) + theme_bw(base_size=12) +
    scale_x_date(name=NULL, date_breaks='10 years', limits=c(ymd('1954-01-01'), ymd(paste0(max(dataset$year)+1,'-01-01'))), date_labels='%Y', minor_breaks = NULL) +
    scale_y_continuous(limits=c(300, 25+round(max(dataset$average),-1)), breaks=seq(300, round(max(dataset$average)+25,-1), 25)) +
    geom_line(aes(y=trend), linewidth=1, col='firebrick1') +
    labs(title=expression('Atmospheric '*CO[2]*' (Keeling Curve)'), subtitle=expression('Mauna Loa '*CO[2]*' monthly mean ppm'),
    y=expression(CO[2]*' concentration in air' ), caption='Source: NOAA/ESRL and Scripps Institution of Oceanography.\nhttps://gml.noaa.gov/ccgg/trends/data.html')

if (annot) {

dt <- pull(slice(dataset, which.max(date)), date)
vl <- pull(slice(dataset, which.max(date)), average)

plot <- plot + annotate("text",x=as.Date('1968-01-01'), y=440, label=paste(dt, vl,sep=": "), color='red')
}

if (print) print(plot)
invisible(plot)
}
