# seminar-exports.R
# Writes every export from part 5 to the output/ folder:
#   Table 1 as RTF and HTML; the sepsis figures as PNG, SVG, and PDF;
#   the clickable patient paths as an interactive HTML page;
#   and a Word report and a PowerPoint deck.
#
# Run it from the lesson folder, with these files in data/:
#   moorfields_baseline.csv, ghana_sepsis_samples.csv, ghana_sepsis_heatmaps.csv,
#   moorfields-table.R, and sepsis-figures.R
#
# Install the packages once, in the console:
# install.packages(c("gtsummary", "gt", "ggplot2", "patchwork", "ragg", "svglite",
#                    "plotly", "htmlwidgets", "rmarkdown",
#                    "flextable", "officer", "rvg"))

library(gt)
library(flextable)
library(officer)
library(rvg)

source("data/moorfields-table.R")
source("data/sepsis-figures.R")

dir.create("output", showWarnings = FALSE)

# Table 1 ---------------------------------------------------------------------

writeLines(gt::as_rtf(table_gt), "output/moorfields_table1.rtf")
writeLines(gt::as_raw_html(table_gt, inline_css = FALSE),
           "output/moorfields_table1.html")

# Figures as PNG, each at the size it needs -----------------------------------

save_png <- function(plot, file, width, height, units = "in") {
  ggplot2::ggsave(file.path("output", file), plot = plot,
                  device = ragg::agg_png, width = width, height = height,
                  units = units, dpi = 300, bg = "white")
}

heatmap_export <- pattern_heatmap + labs(caption = source_note)
journal_trajectory <- trajectory + theme_classic(base_size = 8)

save_png(figure, "sepsis_pc1_boxplot.png", width = 7, height = 5)
save_png(trajectory, "sepsis_trajectory.png", width = 7, height = 5)
save_png(paths, "sepsis_paths.png", width = 8, height = 4)
save_png(heatmap_export, "sepsis_heatmap.png", width = 7, height = 7)
save_png(journal_trajectory, "sepsis_trajectory_183mm.png",
         width = 183, height = 120, units = "mm")

# Figures as vector files -----------------------------------------------------

ggplot2::ggsave("output/sepsis_pc1_boxplot.svg", plot = figure,
                device = svglite::svglite, width = 7, height = 5,
                units = "in", bg = "white")
ggplot2::ggsave("output/sepsis_six_heatmaps.pdf", plot = six_panels,
                width = 12, height = 7, units = "in")

# Interactive patient paths ---------------------------------------------------
# selfcontained = TRUE needs Pandoc, which comes with RStudio.

library(plotly)

patient_key <- highlight_key(patients, ~patient_id)

clickable <- ggplot(patient_key, aes(
    x = P23, y = P4, group = patient_id, colour = outcome,
    text = paste0("Patient ", patient_id,
                  "<br>Visit: ", visit,
                  "<br>Pattern 23: ", round(P23, 2),
                  "<br>Pattern 4: ", round(P4, 2))
  )) +
  geom_path(alpha = 0.3) +
  geom_point(size = 1) +
  facet_wrap(~ outcome) +
  scale_colour_manual(values = line_colours) +
  labs(x = "Pattern 23 value", y = "Pattern 4 value", colour = "28-day outcome") +
  theme_classic(base_size = 12)

interactive_paths <- ggplotly(clickable, tooltip = "text") |>
  plotly::highlight(on = "plotly_click", color = "black")

htmlwidgets::saveWidget(
  interactive_paths, "output/sepsis_paths_interactive.html",
  selfcontained = TRUE, title = "Ghana sepsis cohort: patient paths"
)

# Word report -----------------------------------------------------------------

ft <- as_flex_table(tbl, include = -autofit) |>
  theme_booktabs() |>
  bg(bg = "#003B49", part = "header") |>
  color(color = "white", part = "header") |>
  fontsize(size = 9, part = "all") |>
  width(j = 1, width = 2.7) |>
  width(j = 2:6, width = 0.7)

report <- read_docx() |>
  docx_set_paragraph_style(
    style_id = "Title", style_name = "Title",
    fp_t = fp_text(font.family = "Arial", font.size = 22,
                   bold = TRUE, color = "black")
  ) |>
  body_add_par("Seminar report: Table 1 and sepsis figures", style = "Title") |>
  body_add_flextable(ft) |>
  body_add_break() |>
  body_add_img("output/sepsis_pc1_boxplot.png",
               width = 6.2, height = 6.2 * 5 / 7) |>
  body_add_par("Figure 1. PC1 scores by visit and 28-day outcome.",
               style = "Normal") |>
  body_add_break() |>
  body_add_img("output/sepsis_heatmap.png", width = 6.2, height = 6.2) |>
  body_add_par("Figure 2. Pattern z-scores by group and visit.",
               style = "Normal")

print(report, target = "output/seminar_report.docx")

# PowerPoint deck -------------------------------------------------------------

ft_slide <- ft |>
  fontsize(size = 14, part = "all") |>
  width(j = 1, width = 3.0) |>
  width(j = 2:6, width = 1.1)

slides <- read_pptx() |>
  add_slide(layout = "Title and Content", master = "Office Theme") |>
  ph_with("Table 1. Baseline characteristics", ph_location_type("title")) |>
  ph_with(ft_slide, ph_location(left = 0.5, top = 1.5)) |>
  add_slide(layout = "Title and Content", master = "Office Theme") |>
  ph_with("Survivors move towards healthy donors", ph_location_type("title")) |>
  ph_with(dml(ggobj = trajectory), ph_location_type("body")) |>
  add_slide(layout = "Title Only", master = "Office Theme") |>
  ph_with("Pattern z-scores by group and visit", ph_location_type("title")) |>
  ph_with(external_img("output/sepsis_heatmap.png", width = 5.5, height = 5.5),
          ph_location(left = 2.25, top = 1.6, width = 5.5, height = 5.5))

print(slides, target = "output/seminar_slides.pptx")

message("Done. The exported files are in the output/ folder.")
