#' Plot gistic results along linearized chromosome
#' @description A genomic plot with segments highlighting signififcant Amplifications and Deletion regions.
#' @param gistic an object of class \code{GISTIC} generated by \code{readGistic}
#' @param fdrCutOff fdr cutoff to use. Default 0.1
#' @param markBands any cytobands to label. If 'all' labels all significantly altered cytobands (below fdrCuoff)
#' @param markBandsCol color for highlighted region
#' @param color colors for Amp and Del events.
#' @param ref.build reference build. Could be hg18, hg19 or hg38.
#' @param cytobandOffset if scores.gistic file is given use this to adjust cytoband size.
#' @param file if given saves plot as a pdf.
#' @param width width of the file to be saved.
#' @param height height of the file to be saved.
#' @examples
#' all.lesions <- system.file("extdata", "all_lesions.conf_99.txt", package = "maftools")
#' amp.genes <- system.file("extdata", "amp_genes.conf_99.txt", package = "maftools")
#' del.genes <- system.file("extdata", "del_genes.conf_99.txt", package = "maftools")
#' scores.gistic <- system.file("extdata", "scores.gistic", package = "maftools")
#' laml.gistic = readGistic(gisticAllLesionsFile = all.lesions, gisticAmpGenesFile = amp.genes, gisticDelGenesFile = del.genes, gisticScoresFile = scores.gistic)
#' gisticChromPlot(laml.gistic)
#' @return nothing
#' @export

gisticChromPlot = function(gistic = NULL, fdrCutOff = 0.1, markBands = NULL, markBandsCol = 'purple',
                           color = NULL, ref.build = "hg19", cytobandOffset = 0.01, file = NULL, width = 6, height = 5){

  g = getCytobandSummary(gistic)
  g = g[qvalues < fdrCutOff]
  g[,Chromosome := sapply(strsplit(x = g$Wide_Peak_Limits, split = ':'), '[', 1)]
  g[,loc := sapply(strsplit(x = g$Wide_Peak_Limits, split = ':'), '[', 2)]
  g[,Start_Position := sapply(strsplit(x = g$loc, split = '-'), '[', 1)]
  g[,End_Position := sapply(strsplit(x = g$loc, split = '-'), '[', 2)]
  g.lin = transformSegments(segmentedData = g[,.(Chromosome, Start_Position, End_Position, qvalues, Cytoband, Variant_Classification)])

  if(is.null(color)){
    color = c('Amp' = 'red', 'Del' = 'blue')
  }

  gis.scores = transformSegments(segmentedData = gistic@gis.scores, build = ref.build)
  gis.scores$amp = ifelse(test = gis.scores$Variant_Classification == 'Del', yes = -gis.scores$G_Score-cytobandOffset, no = gis.scores$G_Score+cytobandOffset)
  gis.scores$ystart = ifelse(test = gis.scores$Variant_Classification == 'Del', yes = -cytobandOffset, no = cytobandOffset)
  fdrCutOff = -log10(fdrCutOff)
  gis.scores$Variant_Classification = ifelse(test = as.numeric(gis.scores$fdr) > fdrCutOff, yes = gis.scores$Variant_Classification, no = 'neutral')
  gis.scores$Variant_Classification = factor(gis.scores$Variant_Classification, levels = c('neutral', 'Amp', 'Del'))

  if(ref.build == 'hg19'){
    chr.lens = c(249250621, 243199373, 198022430, 191154276, 180915260, 171115067, 159138663,
                 146364022, 141213431, 135534747, 135006516, 133851895, 115169878, 107349540,
                 102531392, 90354753, 81195210, 78077248, 59128983, 63025520, 48129895, 51304566,
                 155270560, 59373566)
  } else if(ref.build == 'hg18'){
    chr.lens = c(247249719, 242951149, 199501827, 191273063, 180857866, 170899992,
                 158821424, 146274826, 140273252, 135374737, 134452384, 132349534,
                 114142980, 106368585, 100338915, 88827254, 78774742, 76117153,
                 63811651, 62435964, 46944323, 49691432, 154913754, 57772954)
  } else if(ref.build == 'hg38'){
    chr.lens = c(248956422, 242193529, 198295559, 190214555, 181538259, 170805979,
                 159345973, 145138636, 138394717, 133797422, 135086622, 133275309,
                 114364328, 107043718, 101991189, 90338345, 83257441, 80373285,
                 58617616, 64444167, 46709983, 50818468, 156040895, 57227415)
  }else{
    stop("ref.build can only be hg18, hg19 or hg38")
  }

  chr.lens.cumsum = cumsum(chr.lens)
  nchrs = length(unique(gis.scores$Chromosome))
  chr.labels= c(1:22, 'X', 'Y')
  chr.tbl = data.table::data.table(chr = chr.labels, start = c(1, chr.lens.cumsum[1:length(chr.lens.cumsum)-1]), end = chr.lens.cumsum)
  chr.tbl$color = c('black', 'white')

  gist.gg = ggplot(data = gis.scores[Variant_Classification %in% 'neutral'], aes(x = Start_Position_updated, xend = End_Position_updated, y= ystart , yend = amp, color = Variant_Classification))+
    geom_segment(alpha = 0.6)+geom_segment(data = gis.scores[!Variant_Classification %in% 'neutral'], alpha = 0.6)+cowplot::theme_cowplot(line_size = 1, font_size = 12)+theme(legend.position = 'none')+
    scale_color_manual(values = c('Amp'  ='red', 'Del' = 'blue', 'neutral' = 'gray70'))+ylab('G Score')+
    theme(axis.line.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.x = element_blank(),
          axis.title.y = element_text(face = "bold"), axis.text.y = element_text(face = "bold"))+
    geom_rect(data = chr.tbl, aes(xmin = start, xmax = end, ymin = -cytobandOffset, ymax = cytobandOffset), fill = chr.tbl$color, inherit.aes = FALSE, alpha = 0.9)

  if(!is.null(markBands)){

    if(all(length(markBands) == 1 & markBands == 'all')){
      mb = g.lin
    }else{
      mb = g.lin[Cytoband %in% markBands]
    }

    if(nrow(mb) == 0){
      message("Available cytobands: ")
      print(getCytobandSummary(x = gistic)[qvalues < fdrCutOff])
      stop(paste("Could not find provided cytobands:", paste(markBands, collapse = ", ")))
    }

    mb[,ysmall := min(gis.scores[,amp], na.rm = TRUE)]
    mb[,ybig := max(gis.scores[,amp], na.rm = TRUE)]
    mb$labPos =ifelse(test = mb$Variant_Classification == 'Amp', yes = mb$ybig, no = mb$ysmall)

    gist.gg = gist.gg+
      ggrepel::geom_text_repel(data = mb, aes(x = Start_Position_updated, y = labPos, label = Cytoband), inherit.aes = FALSE, size = 4, fontface = 'bold')+
      geom_segment(data = mb, aes(x = Start_Position_updated, xend = End_Position_updated,
                                   y = ysmall, yend = ybig, label = Cytoband), color = markBandsCol, alpha = 0.25)
  }

  if(!is.null(file)){
    cowplot::save_plot(filename = paste(file, 'pdf', sep='.'), plot = gist.gg, base_height = height, base_width = width)
  }

  gist.gg
}
