knitr::opts_chunk$set(echo=FALSE, warning = FALSE)

library(readr)
library(tidyverse)
library(janitor)
library(scales)


sticky_bun <- read_csv("./data/Sticky bun dataset - stick_bun.csv", 
    col_types = cols(`day of week` = col_integer()), 
    na = "0") |>
  janitor::clean_names()

sticky_bun_visits <- nrow(sticky_bun)

sticky_bun$date <- lubridate::as_date(sticky_bun$date)

sticky_bun <- sticky_bun |>
  group_by(date) |>
  summarise(total_sticky_bun = sum(sticky_bun))

sticky_bun <- sticky_bun |> 
  mutate(week = lubridate::week(date)) |>
  replace_na(list(total_sticky_bun = 0)) |>
  mutate(name_dow = lubridate::wday(date, label = TRUE, abbr = TRUE )) |>
  mutate(day_of_week = lubridate::wday(date)) |>
  mutate(year = lubridate::year(date))

distinct_dates <- sticky_bun |> distinct(date)

sticky_bun <- sticky_bun |> select(date, day_of_week, total_sticky_bun, year, week, name_dow)


gh_waffle <- function(data, pal = "D", dir = -1) {
  p <- ggplot(data, aes(x = week, y = name_dow, fill = total_sticky_bun)) +
   
     scale_fill_viridis_c(
      name = "Sticky buns",
      option = pal, # Variable color palette
      direction = dir, # Variable color direction
    #  na.value = "yellow",
      limits = c(0, max(data$total_sticky_bun))
    ) +
    
   
    
    geom_tile(color = "white", size = 0.7) +
    facet_wrap("year", ncol = 1) +
   

     scale_x_continuous(
      expand = c(0, 0),
      breaks = seq(1, 52, length = 12),
      labels = c(
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
      )
    ) +

    theme(
      axis.title = element_blank(),
      axis.ticks = element_blank(), 
      axis.text.y = element_text(size = 7),
      panel.grid = element_blank(),
      legend.position = "bottom",
      #aspect.ratio = 1/3,
      legend.key.width = unit(1, "cm"),
      strip.text = element_text(hjust = 0.00, face = "bold", size = 12)
    )

  
}
#improvements desired
#better alignment of the month names
#improve the gh_waffle graph function to not need the heavy manipulation
#of the x scale


#| fig-width: 8
#| fig-height: 5
plot_sticky_bun <- gh_waffle(sticky_bun) + 
  labs(title = "Sticky Bun Purchases by Day of the Week")

plot_sticky_bun

#ggsave('plot_sticky_bun.png')

