#! /usr/bin/env Rscript

# Configuration and libraries ---------------------------------------------

# Where should we store the generated plot images?
# Default is the current directory
destdir <- "."

# What graphics format should we use?  Use one of the valid device
# option strings from the ggsave command, eg "svg", "png", "pdf".
# If you want to save to an svg file, as below, you will have to also
# run the following once inside R:
#   install.packages("svglite")
# This in turn might need other libraries to be installed on your system:
# follow the instructions given in the error messages if there are any.
# The default is to save to a png
output_format <- "png"

# To load the required packages, either:
# library(tidyverse)
# or more efficiently, you could just load the specific packages needed:
# library(dplyr)
# library(stringr)
# library(ggplot2)
# The following version loads the tidyverse with no warning messages
# A similar approach could be used to load the specific packages instead
suppressMessages(library("tidyverse", character.only = TRUE,
                         quietly = TRUE, warn.conflicts = FALSE))

# To install these packages onto your system, run inside R either:
#   install.packages("tidyverse")
# or the more specific:
#   install.packages("dplyr")
#   install.packages("stringr")
#   install.packages("ggplot2")

library(googlesheets4)
# Install this package using:
#   install.packages("devtools")
#   devtools::install_github("tidyverse/googlesheets4")
# The Google sheet is publicly readable, so we do not need to authenticate
sheets_deauth()

# Reading in the data -----------------------------------------------------

sheet_id <- "1ZxN9NN2lWX-ACsccMchnoMwI5-qFZDhn4EYzqbYYtPc"

read_google_sheet <- function(sheet_number, ncols) {
  if (ncols == 2) {
    col_names <- c("time", "est")
    col_types <- "Tn"
  }
  else {
    col_names <- c("time", "primer_resp", "est")
    col_types <- "Tcn"
  }

  # We use suppressMessages as the read_sheet function is quite noisy
  # We specify the column types so that numbers with funny formats such
  # as "00000000000000001" are correctly interpreted as numbers and not
  # as strings.
  sheet <- suppressMessages(read_sheet(sheet_id, sheet = sheet_number,
                                       skip = 1, col_names = col_names,
                                       col_types = col_types))
  # Only keep estimates which are positive, to filter out any silly
  # entries with zero or negative population estimates; this also filters
  # out any entries with missing estimates
  sheet %>% filter(est > 0)
}

pop30 <- read_google_sheet(sheet_number = 1, ncols = 3) %>%
  mutate(primer = "> 30 ?",
         primer_logic = primer_resp == "Yes",
         primer_resp_str = str_c("> 30 ? - ", primer_resp))

pop70 <- read_google_sheet(sheet_number = 2, ncols = 3) %>%
  mutate(primer = "> 70 ?",
         primer_logic = primer_resp == "Yes",
         primer_resp_str = str_c("> 70 ? - ", primer_resp))

pop00 <- read_google_sheet(sheet_number = 3, ncols = 2) %>%
  mutate(primer = "none", primer_logic = NA, primer_resp = "",
         primer_resp_str = "none")

pops <- bind_rows(pop30, pop70, pop00) %>%
  select(primer, primer_logic, primer_resp_str, est, time) %>%
  arrange(primer, primer_logic, est)

counts <- pops %>%
  group_by(primer) %>%
  count() %>%
  mutate(cnt = str_c("n = ", n))

counts2 <- pops %>%
  group_by(primer_resp_str) %>%
  count() %>%
  mutate(cnt = str_c("n = ", n))

# plot1 -------------------------------------------------------------------
# This plot shows the data grouped according to the primer question

plot1 <- ggplot(data = pops, mapping = aes(x = primer, y = est)) +
  geom_boxplot() +
  geom_text(data = counts, aes(x = primer, y = -10, label = cnt),
            size = 3) +
  labs(x = "Primer question asked", y = "Population estimate (millions)",
       caption = str_c("Plot last updated: ",
                       format(Sys.time(), "%a %d %b %X %Y %Z"))) +
  theme(axis.text.x = element_text(size = 12, color = "red",
                                   face = "bold")) +
  geom_segment(aes(x = 0.5, y = 30, xend = 1.5, yend = 30),
               color = "red", linetype = "dotted", size = 1) +
  geom_segment(aes(x = 1.5, y = 70, xend = 2.5, yend = 70),
               color = "red", linetype = "dotted", size = 1) +
  geom_hline(yintercept = 105, color = "cadetblue1") + 
  geom_hline(yintercept = 0, color = "black") + 
  coord_cartesian(xlim = c(0.5, 3.5), ylim = c(-15, 150), expand = FALSE)  
ggsave(str_c("philippines-plot.", output_format), plot = plot1,
       device = output_format,
       path = destdir, width = 4, height = 4, units = "in")


# plot2 -------------------------------------------------------------------
# This plot shows the data grouped according to the primer question
# and response received

plot2 <- ggplot(data = pops, mapping = aes(x = primer_resp_str, y = est)) +
  geom_boxplot() +
  geom_text(data = counts2, aes(x = primer_resp_str, y = -10, label = cnt),
            size = 3) +
  labs(x = "Primer question and response",
       y = "Population estimate (millions)",
       caption = str_c("Plot last updated: ",
                       format(Sys.time(), "%a %d %b %X %Y %Z"))) +
  theme(axis.text.x = element_text(size = 12, color = "red",
                                   face = "bold")) +
  geom_segment(aes(x = 0.5, y = 30, xend = 2.5, yend = 30),
               color = "red", linetype = "dotted", size = 1) +
  geom_segment(aes(x = 2.5, y = 70, xend = 4.5, yend = 70),
               color = "red", linetype = "dotted", size = 1) +
  geom_hline(yintercept = 105, color = "cadetblue1") + 
  geom_hline(yintercept = 0, color = "black") + 
  coord_cartesian(xlim = c(0.5, 5.5), ylim = c(-15, 150), expand = FALSE)
ggsave(str_c("philippines-plot2.", output_format), plot = plot2,
       device = output_format,
       path = destdir, width = 6, height = 4, units = "in")
