#!/usr/bin/env Rscript

suppressPackageStartupMessages({
  library(data.table)
  library(ggplot2)
})

setDTthreads(8)

# ======================
# INPUT
# ======================

pn_file <- "/BLUES/eric/ONT/5hmc_DMR/DMR_1kb_5hmC_abs_Naive_vs_Primed_30x.tsv"
tn_file <- "/BLUES/eric/ONT/5hmc_DMR/DMR_1kb_5hmC_abs_TSC_vs_Naive_30x.tsv"

out_pdf <- "/BLUES/eric/ONT_WGBS/Figure_5/DhMR_direction_barplot.pdf"

# ======================
# LOAD
# ======================

pn <- fread(pn_file)
tn <- fread(tn_file)

# ======================
# COUNT
# ======================

pn_up   <- nrow(pn[Naive_minus_Primed > 0])
pn_down <- nrow(pn[Naive_minus_Primed < 0])

tn_up   <- nrow(tn[TSC_minus_Naive > 0])
tn_down <- nrow(tn[TSC_minus_Naive < 0])

plot_dt <- data.table(
  Comparison = c(
    "Naive vs Primed",
    "Naive vs Primed",
    "TSC vs Naive",
    "TSC vs Naive"
  ),

  Direction = c(
    "Delta 5hmC > 0.05",
    "Delta 5hmC < -0.05",
    "Delta 5hmC > 0.05",
    "Delta 5hmC < -0.05"
  ),

  Count = c(
    pn_up,
    pn_down,
    tn_up,
    tn_down
  )
)

# ======================
# TOTAL LABELS
# ======================

total_dt <- plot_dt[
  ,
  .(Total = sum(Count)),
  by = Comparison
]

# ======================
# COLORS
# ======================

cols <- c(
  "Delta 5hmC > 0.05" = "#D55E5E",
  "Delta 5hmC < -0.05" = "#4C72B0"
)

# ======================
# PLOT
# ======================

p <- ggplot(
  plot_dt,
  aes(
    x = Comparison,
    y = Count,
    fill = Direction
  )
) +

  geom_bar(
    stat = "identity",
    width = 0.65
  ) +

  geom_text(
    aes(label = Count),
    position = position_stack(vjust = 0.5),
    size = 5,
    color = "white",
    fontface = "bold"
  ) +

  geom_text(
    data = total_dt,
    aes(
      x = Comparison,
      y = Total,
      label = Total
    ),
    inherit.aes = FALSE,
    vjust = -0.5,
    size = 6,
    fontface = "bold"
  ) +

  scale_fill_manual(values = cols) +

  expand_limits(
    y = max(total_dt$Total) * 1.08
  ) +

  labs(
    title = "Dynamic 5hmC methylated regions (DhMR)",
    subtitle = "1 kb windows, |Delta 5hmC| > 0.05, minimum CpG coverage = 30x",
    x = NULL,
    y = "DhMR windows",
    fill = NULL
  ) +
  
  theme_bw(base_size = 16) +

  theme(
    plot.title = element_text(
      hjust = 0.5,
      face = "bold",
      size = 24
    ),
  
    plot.subtitle = element_text(
      hjust = 0.5,
      size = 15
    ),
  
    legend.position = "right",
  
    legend.text = element_text(
      size = 15
    ),
  
    axis.text.x = element_text(
      face = "bold",
      size = 18
    ),
  
    axis.text.y = element_text(
      size = 15
    ),
  
    axis.title.y = element_text(
      size = 20,
      face = "bold"
    ),
  
    plot.margin = margin(
      t = 25,
      r = 30,
      b = 15,
      l = 40
    )
  )

# ======================
# SAVE
# ======================

ggsave(
  out_pdf,
  p,
  width = 12,
  height = 7,
  limitsize = FALSE
)