#' Download and plot essential climate data
#'
#' Retrieves globally averaged marine surface methane monthly mean data from National Oceanic and Atmospheric Administration.
#' The Global Monitoring Division of NOAA’s Earth System Research Laboratory has measured methane since 1983 at a globally distributed network of air sampling sites.
#' A global average is constructed by first smoothing the data for each site as a function of time, and then smoothed values for each site are plotted as a function of latitude.
#' Global means are calculated from the latitude plot at each time step.
#' \url{https://gml.noaa.gov/ccgg/trends_ch4/}
#' \url{https://gml.noaa.gov/ccgg/about/global_means.html}
#'
#' @name get_methane
#' @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 methane series
#'
#' @details `get_methane` invisibly returns a tibble with NOAA's monthly globally averaged methane measurement.
#' The returned object includes year, month, date, average, average uncertainty, trend, and trend uncertainty columns.
#' Trend is NOAA's published trend.  Please refer to above website for details. CH4 expressed as a mole fraction in dry air, nanomol/mol, abbreviated as ppb.
#'
#' @importFrom readr read_table
#' @importFrom lubridate ymd ceiling_date
#' @importFrom utils download.file
#'
#' @examples
#' \donttest{
#' # Fetch from cache if available, otherwise download:
#' ch4 <- get_methane()
#' #
#' # Force fetch from source:
#' ch4 <- get_methane(use_cache=FALSE)
#' #
#' # Review cache contents and last update dates:
#' hockeystick_cache_details()
#' #
#' # Plot output using package's built-in ggplot2 settings
#' plot_methane(ch4) }
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#' @references
#' Lan, X., K.W. Thoning, and E.J. Dlugokencky: Trends in globally-averaged CH4, N2O, and SF6 determined from NOAA Global Monitoring Laboratory measurements. Version 2022-11, \doi{10.15138/P8XG-AA10}
#'
#' @export
get_methane <- 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,'methane.rds'))) return(invisible(readRDS((file.path(hs_path,'methane.rds')))))
  }

file_url <- 'https://gml.noaa.gov/webdata/ccgg/trends/ch4/ch4_mm_gl.txt'
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))}

ch4 <- suppressMessages( read_table(dl, col_names = FALSE, skip = 65) )
colnames(ch4) <- c('year', 'month', 'date', 'average', 'average_unc', 'trend','trend_unc')
ch4$date <- ceiling_date(ymd(paste(ch4$year, ch4$month, '01',sep='-')), unit='month')-1

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

invisible(ch4)
}



#' Download and plot essential climate data
#'
#' Plots atmospheric methane data retrieved using `get_methane()` with ggplot2. The output ggplot2 object may be modified.
#'
#'
#' @name plot_methane
#' @param dataset Name of the tibble generated by `get_methane`
#' @param print (boolean) Display methane 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 methane chart
#'
#' @details `plot_methane` invisibly returns a ggplot2 object with a pre-defined methane chart using data from `get_methane`.
#' By default the chart is also displayed. Users may further modify the output ggplot2 chart.
#'
#' @import ggplot2
#' @importFrom dplyr pull slice
#'
#' @examples
#' \donttest{
#' # Fetch methane data:
#' ch4 <- get_methane()
#' #
#' # Plot output using package's built-in ggplot2 defaults
#' plot_methane(ch4)
#'
#' # Or just call plot_methane(), which defaults to get_methane() dataset
#' plot_methane()
#'
#' p <- plot_methane(ch4, print = FALSE)
#' # Modify plot such as: p + ggplot2::labs(title='Trend in Atmospheric Methane') }
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#'
#' @export

plot_methane <- function(dataset = get_methane(),
                        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('1983-01-01'), ymd(paste0(max(dataset$year)+1,'-01-01'))), date_labels='%Y', minor_breaks = NULL) +
    scale_y_continuous(limits=c(1600, round(max(dataset$average),-3)), breaks=seq(1600, round(max(dataset$average),-3), 50)) +
    geom_line(aes(y=trend), linewidth=1, col='firebrick1') +
    labs(title=expression('Atmospheric Methane'), subtitle=expression('Globally Averaged Atmospheric '*CH[4]*' monthly mean ppb'),
    y=expression(CH[4]*' mole fraction (ppb)' ), caption='Source: NOAA/ESRL.\nhttps://gml.noaa.gov/ccgg/trends_ch4/')

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('1989-01-01'), y=1970, label=paste(dt, vl,sep=": "), color='red')
}

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