#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)
print(args)

suppressPackageStartupMessages(library(dplyr))
library(stringr)
suppressPackageStartupMessages(library(circlize))

#prepare table
read_interaction_table <-
  as.data.frame(
    read.table(
      args[1],
      header = TRUE,
      sep = "\t"
    )
  )
print(dim(read_interaction_table))
print(head(read_interaction_table))
print(colnames(read_interaction_table))

expected_colnames<-c("read_id","pos1","chr1","family1","pos2","chr2","family2")
stopifnot(colnames(read_interaction_table)==expected_colnames)

#load chromosomes
chromosome_file <-
  args[2]

#load genes
#gene_track <-
#  as.data.frame(
#    read.table(
#      args[3],
#      sep = "\t"
#    )
#  )
#coordinates_gene <- as.data.frame(gene_track[, c(1, 4, 5)]) #chromosome start end

#load repeats
#repeat_track <-
#  as.data.frame(
#    read.table(
#      args[4],
#      sep = "\t"
#    )
#  )
#coordinates_repeat <- as.data.frame(repeat_track[, c(1, 4, 5)]) #chromosome start end

#filter long range

#subset to proper families
family1_unique <-as.vector(unique(sort(read_interaction_table$family1)))
family2_unique <-as.vector(unique(sort(read_interaction_table$family2)))

familiesToPlot<-sort(unique(c(family1_unique,family2_unique)))

print(familiesToPlot)
#pairs <- as.data.frame(t(as.data.frame(combn(familiesToPlot, 2))))
pairs <- as.data.frame(t(cbind(combn(familiesToPlot, 2),rbind(familiesToPlot,familiesToPlot))))

plotCircos <- function(family1, family2, interactions) {
  if (nrow(interactions) >= 1) {
    png(
      file = paste0(str_replace(family1,"/","_"), "_", str_replace(family2,"/","_"), ".png"),
      units = "in",
      width = 6,
      height = 6,
      res = 300
    )
    #load our own rice chromosome lengths because the karyotype from the USCS is not avaiable
    cytoband.df = read.table(
      chromosome_file,
      colClasses = c(
        "character",
        "numeric",
        "numeric",
        "character",
        "character"
      ),
      sep = "\t"
    )

    print(head(cytoband.df))

    circos.initializeWithIdeogram(cytoband.df, sort.chr = FALSE)
    
    #plot annotation tracks for genes and repeats if available
    #if (exists("coordinates_gene")) {
    #  circos.genomicDensity(coordinates_gene,
    #                        window.size = 1e6,
    #                        col = "blue")
    #}
    
    #if (exists("coordinates_repeat")) {
    #  circos.genomicDensity(coordinates_repeat,
    #                        window.size = 1e6,
    #                        col = "red")
    #}
    
    df = data.frame(matrix("", ncol = 3, nrow = nrow(interactions)))
    colnames(df) <- c("sectors", "x", "y")
    df$sectors <- as.character(interactions$chr1)
    df$x <- as.numeric(interactions$pos1)
    df$y <- as.numeric(runif(nrow(interactions)))
    
    plotLine <- function(chr1,
                         pos1,
                         chr2,
                         pos2) {
      circos.link(chr1,
                  as.numeric(pos1),
                  chr2,
                  as.numeric(pos2),
                  col = rgb(255, 0, 0, max = 255, alpha = 125)) #transparent red
    }
    
    apply(sample_n(interactions, min(nrow(interactions),500)), 1, function(x) #only plot maximum of 500 lines
      plotLine(x[["chr1"]], x[["pos1"]], x[["chr2"]], x[["pos2"]]))
    
    title(paste0(family1," ",family2,"; n=", nrow(interactions)))

    circos.clear()
    dev.off()  ## file in the current dir
  }
}

plot_if_enough_data <-
  function(family1_to_choose, family2_to_choose) {
    print(paste(family1_to_choose, family2_to_choose))
    reads_from_families <-
      read_interaction_table %>% filter(((family1 == family1_to_choose) &
                               (family2 == family2_to_choose)
      ) |
        ((family2 == family1_to_choose) &
           (family1 == family2_to_choose)
        )) #all these reads have clusters with the desired families
    
    if (nrow(reads_from_families) >= 1) {
      print(paste0("n=", nrow(reads_from_families)))
      plotCircos(family1_to_choose,
                 family2_to_choose,
                 reads_from_families)
    } else {
      print("Not enough data for plotting.")
    }
    
  }

#plot
apply(pairs, 1, function(x)
  plot_if_enough_data(x[1], x[2])) #for each pair, create a plot

