# Original Bopbun demonstration. CC0-1.0. Run in this file's directory.
library(ggplot2)
library(grid)

d <- expand.grid(column = 1:4, row = 1:3)
d$score <- c(2, 8, 4, 14, 6, 10, 12, 3, 9, 5, 11, 7)
write.csv(d, "synthetic.csv", row.names = FALSE)
limits <- c(2, 14)
fill_scale <- scale_fill_gradient(
  low = "#f1e5b6", high = "#264e70", limits = limits,
  breaks = limits, labels = c("Low (2)", "High (14)"), name = "Score"
)
p <- ggplot(d, aes(column, row, fill = score)) +
  geom_tile(colour = "white", linewidth = 1) +
  geom_text(aes(label = score, colour = ifelse(score >= 10, "white", "#18212b")),
            size = 4, fontface = "bold") + scale_colour_identity() +
  fill_scale + coord_fixed() +
  scale_x_continuous(breaks = 1:4) +
  scale_y_continuous(breaks = 1:3) +
  labs(x = "Column", y = "Row") + theme_minimal(base_size = 12) +
  theme(panel.grid = element_blank(), legend.position = "right")
before <- p + guides(fill = guide_colourbar(
  display = "rectangles", nbin = 64,
  theme = theme(legend.key.height = unit(34, "mm"))
))

# Use the trained fill scale so the guide and tiles share the same palette.
trained <- ggplot_build(p)$plot$scales$get_scales("fill")
n <- 64
edges <- seq(limits[1], limits[2], length.out = n + 1)
midpoints <- (head(edges, -1) + tail(edges, -1)) / 2
colours <- trained$map(midpoints)
key <- grobTree(
  rasterGrob(matrix(rev(colours), ncol = 1), x = 0.5, y = 0.5,
             width = 0.22, height = 0.64, interpolate = FALSE),
  textGrob("High (14)", x = 0.5, y = 0.93, gp = gpar(fontsize = 11)),
  textGrob("Low (2)", x = 0.5, y = 0.07, gp = gpar(fontsize = 11))
)
after <- p + guides(
  fill = "none",
  endpoint = guide_custom(key, width = unit(24, "mm"),
                          height = unit(52, "mm"), title = "Score")
)

for (nm in c("before", "after")) {
  png(paste0(nm, ".png"), width = 1200, height = 900, res = 200)
  print(get(nm)); dev.off()
}
pdf("after.pdf", width = 6, height = 4.5, timestamp = FALSE)
print(after); dev.off()
b <- ggplot_build(before)$data[[1]]
a <- ggplot_build(after)$data[[1]]
stopifnot(identical(b, a), sum(d$score) == 91,
          identical(as.character(key$children[[2]]$label), "High (14)"))
write.csv(data.frame(score = midpoints, fill = colours),
          "guide-samples.csv", row.names = FALSE)
write.csv(a, "tile-check.csv", row.names = FALSE)
writeLines(c("12 tile objects identical before/after; score sum=91",
             "64 custom guide bands; high above, low below",
             capture.output(sessionInfo())), "checks.txt")
