#' Download and plot essential climate data
#'
#' Retrieves Global Carbon Project (GCP) annual global carbon dioxide emissions since 1750 from Our World In Data repository
#' \url{https://github.com/owid/co2-data}
#'
#' @name get_emissions
#' @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 annual carbon dioxide emissions
#'
#' @details `get_emissions` invisibly returns a tibble with GCP's annual carbon dioxide emissions from fossil fuels in aggregate and for every nation.
#' The returned object includes ISO code, country, year, co2 emissions, growth rates, per capita, and decompositions by industry and gas type.
#' Please refer to above website for details.
#'
#' @importFrom readr read_csv col_skip cols
#' @importFrom utils download.file
#'
#' @examples
#' \donttest{
#' # Fetch from cache if available:
#' emissions <- get_emissions()
#' #
#' # Force cache refresh:
#' emissions <- get_emissions(use_cache=FALSE)
#' #
#' # Review cache contents and last update dates:
#' hockeystick_cache_details()
#' #
#' # Plot output using package's built-in ggplot2 settings
#' plot_emissions(emissions) }
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#' @references
#' \url{https://www.globalcarbonproject.org/carbonbudget/}
#'
#'
#' Friedlingstein, P. et al (2020), Global Carbon Budget 2020, \emph{Earth System Science Data}, vol. 12, 3269-3340 \doi{10.5194/essd-12-3269-2020}
#' @export
get_emissions <- 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,'emissions.rds'))) return(invisible(readRDS((file.path(hs_path,'emissions.rds')))))
  }

file_url <- 'https://github.com/owid/co2-data/raw/master/owid-co2-data.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))}
emissions <- suppressMessages( read_csv(dl,  col_types = cols(other_industry_co2 = col_skip(), other_co2_per_capita = col_skip())) )

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

invisible(emissions)
}



#' Download and plot essential climate data
#'
#' Plots carbon dioxide emissions retrieved using `get_emissions()` with ggplot2. The output ggplot2 object may be modified. Alternative columns from the dataset may also be plotted.
#'
#'
#' @name plot_emissions
#' @param dataset Name of the tibble generated by `get_emissions`
#' @param print (boolean) Display carbon dioxide emissions 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.
#' @param start_year Year to start plot at. Defaults to 1900. Data is available since 1750.
#' @param region ISO code of region to plot. Defaults to 'OWID_WRL' which signifies entire world.
#' @param field Field from GCP dataset to be plotted, defaults to 'co2'
#' @param title_expression Chart title, defaults to CO2 emissions
#' @param yaxis_expression y-axis label, defaults to Gt CO2 emissions
#'
#'
#' @return Invisibly returns a ggplot2 object with carbon dioxide emissions chart
#'
#' @details `plot_emissions` invisibly returns a ggplot2 object with a pre-defined carbon dioxide emissions chart using data from `get_emissions`.  Use the `field` parameter to select alternative columns from the data set such as co2_per_capita.
#' 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 emissions:
#' emissions <- get_emissions()
#'
#' # Plot output using package's built-in ggplot2 defaults
#' plot_emissions(emissions)
#'
#' # Or just call plot_emissions(), which defaults to get_emissions() dataset
#' plot_emissions()
#'
#' # You can also select a region by name and start year
#' plot_emissions(region='United States', start_year=1950)
#' p <- plot_emissions(emissions, print = FALSE)
#'
#' # Modify plot such as: p + ggplot2::labs(title='Anthropogenic Carbon Emissions')
#'
#' # Plot a different field from GCP dataset
#' plot_emissions(field='co2_per_capita', yaxis_expression=expression(CO[2]*' per capita' ))}
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#'
#' @export

plot_emissions <- function(dataset = get_emissions(),
                  start_year = 1900, region = 'World',
                  field = 'co2', print = TRUE, annot = TRUE,
                  title_expression = expression('Fossil Combustion '*CO[2]*' Emissions'),
                  yaxis_expression = expression('Gt '*CO[2]*' per year' )) {

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

  dataset <- filter(dataset, country == region)
  dataset <- filter(dataset, year >= start_year)
  dataset$co2 <- dataset$co2/1000

plot <- ggplot(dataset, aes(x=year, y=get(field))) +geom_line(linewidth=1, color='firebrick1') + theme_bw(base_size=12) +
  scale_x_continuous(n.breaks = 10, minor_breaks = NULL) + scale_y_continuous(limits = c(0, max(dataset[, field])), n.breaks = 6)  +
  labs(title =  title_expression, subtitle=dataset$country[1], x=NULL,
    y = yaxis_expression, caption='Source: Global Carbon Project and Our World In Data.\nhttps://github.com/owid/co2-data')

if (annot) {

dtmax <- pull(slice(dataset, which.max(year)), year)
dtmin <- pull(slice(dataset, which.min(year)), year)
vl <- pull(slice(dataset, which.max(year)), field)
vl <- round(vl, 1)

plot <- plot + annotate("text", x = dtmin+(dtmax-dtmin)/10, y=vl*0.9, label=paste(dtmax, vl,sep=": "), color='red')
}

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



#' Download and plot essential climate data
#'
#' Plots carbon dioxide emissions (including land use change) retrieved using `get_emissions()` with ggplot2. The output ggplot2 object may be modified. Alternative columns from the dataset may also be plotted.
#'
#'
#' @name plot_emissions_with_land
#' @param dataset Name of the tibble generated by `get_emissions`
#' @param print (boolean) Display carbon dioxide emissions 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.
#' @param start_year Year to start plot at. Defaults to 1900. Data is available since 1750.
#' @param region ISO code of region to plot. Defaults to 'OWID_WRL' which signifies entire world.
#' @param title_expression Chart title, defaults to CO2 emissions
#' @param yaxis_expression y-axis label, defaults to Gt CO2 emissions
#'
#'
#' @return Invisibly returns a ggplot2 object with carbon dioxide emissions chart
#'
#' @details `plot_emissions_with_land` invisibly returns a ggplot2 object with a pre-defined carbon dioxide emissions (including land use change) chart using data from `get_emissions`.
#' By default the chart is also displayed. Users may further modify the output ggplot2 chart.
#'
#' @import ggplot2
#' @importFrom dplyr pull slice
#' @importFrom stats na.omit
#'
#' @examples
#' \donttest{
#' # Fetch carbon dioxide emissions:
#' emissions <- get_emissions()
#'
#' # Plot output (including land use change) using package's built-in ggplot2 defaults
#' plot_emissions_with_land(emissions)
#'
#' # Or just call plot_emissions_with_land(), which defaults to get_emissions() dataset
#' plot_emissions_with_land()
#'
#' # You can also select a region by name and starting year
#' plot_emissions_with_land(region='United States', start_year=1950)
#' p <- plot_emissions_with_land(emissions, print = FALSE)
#'
#' # Modify plot such as: p + ggplot2::labs(title='Anthropogenic Carbon Emissions')}
#'
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#'
#' @export

plot_emissions_with_land <- function(dataset = get_emissions(),
                           start_year = 1900, region = 'World',
                           print = TRUE, annot = TRUE,
                           title_expression = expression('Fossil + Land Use Change '*CO[2]*' Emissions'),
                           yaxis_expression = expression('Gt '*CO[2]*' per year' )) {

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

  dataset <- filter(dataset, country == region & year >= start_year)
  dataset <- select(dataset, year, country, co2, land_use_change_co2)
  maxcombo <- max(dataset$co2+dataset$land_use_change_co2)/1000
  dataset <- pivot_longer(dataset,-c(year,country), values_to = c("co2"))
  dataset <- na.omit(mutate(dataset, co2=co2/1000))

  plot <- ggplot(dataset, aes(x=year, y=co2, fill=name)) +geom_area(linewidth=1, position='stack') + theme_bw(base_size=12) +
    scale_x_continuous(n.breaks = 10, minor_breaks = NULL) + theme(legend.position=c(0.18, 0.85), legend.title = element_blank()) +
    scale_y_continuous(limits = c( min(0, 1.2*min(dataset[, "co2"])) , 1.2*maxcombo ), n.breaks = 6) +
    scale_fill_manual(labels=c('Fossil Combustion', 'Land Use Change'), values=c("firebrick1","burlywood4")) +
    labs(title =  title_expression, subtitle=dataset$country[1], x=NULL, y = yaxis_expression, caption='Source: Global Carbon Project and Our World In Data.\nhttps://github.com/owid/co2-data')

  if (annot) {

    dtmax <- pull(slice(dataset, which.max(year)), year)
    dtmin <- pull(slice(dataset, which.min(year)), year)
    sumco2 <- filter(dataset, year==dtmax)
    vl <- as.numeric(summarize(sumco2, sum(co2)))
    #vl <- round(vl, 1)

    plot <- plot + annotate("text", x = dtmin+(dtmax-dtmin)/12, y=vl*0.9, label=paste(dtmax, signif(vl, 2),sep=": "), color='red')
  }

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