
message("MCQRBegin: check_mcqr_package_install")

want.mcqr.version <- "1.0.2"
want.mcqr.url <- "https://forgemia.inra.fr/-/project/1534/uploads/6550076d01dab32a562598f355b17938/MCQR_1.0.2.tar.gz"

# check if package "MCQR" is installed
if (!is.installed("MCQR")){
  install.packages(want.mcqr.url, repo=NULL, type="source")
}
if(packageVersion("MCQR") < want.mcqr.version) {
  install.packages(want.mcqr.url, repo=NULL, type="source")
}

library("MCQR", verbose=FALSE)
library("xtable")
library("svglite")
library("readODS")
library(data.table)



message("MCQRBegin: load");


cat("<h2>Load XIC data</h2>")

cat("<p>Loading MassChroq data. NB: peptide intensities measured as peak areas are automatically log10-transformed.</p>")
cat("<p>Directory names must not include a trailing backslash or slash on Windows</p>")

#Load here the protein and peptide TSV files produced by masschroq-export
XICRAW <- mcq.read.masschroq(protFile = "/home/olangella/Téléchargements/demo/proteins.tsv", pepFile = "/home/olangella/Téléchargements/demo/peptides_All_samples.tsv")

cat("<p>Overview of the content of the 'XICRAW' object</p>")
summary(XICRAW)

#prepare a metadata file to describe features of each MS run samples
  META <- mcq.read.metadata("/home/olangella/Téléchargements/demo/metadata.ods")

  cat("<p>Attaching metadata to quantification data</p>")
  cat("<h1>Merging metadata</h1>")
  XICRAW <- mcq.add.metadata(XICRAW, metadata=META)

  cat("<p>Overview of the content of the 'XICRAW' object</p>")
  summary (XICRAW)



    XIC <- XICRAW

  cat("<h3>Normalizing peptide-mz intensities</h3>")

  cat("<p>Normalizing peptide-mz intensities to take into account possible global quantitative variations between LC-MS runs</p>")
  cat("<p>############# Normalizing peptide-mz intensities</p>")

  XIC <- mcq.compute.normalization(XIC, method="median.RT")


  cat("<h4>Control the normalization effets</h4>")
  cat("<p>Checking the median intensity along the chromatography after normalization.</p>")
  mcq.plot.intensity.profile(XIC, factorToColor=c(), RTinterval=), file=stderr()
  cat("<p>############# Controling the effect of normalization on intensities distribution</p>")
  cat("<p># Display of the graph of intensity distributions on the screen</p>")
  mcq.plot.intensity.violin(XIC, factorToColor=c()) ;

  cat("<h4>Principal Component Analysis</h4>")
  cat("<p>PCA using all the samples as individuals</p>")
  XIC_PCA <- mcq.compute.pca(XIC), file=stderr());
  cat("<p>Display of the PCA on the screen. Possibility to modify the 'factorToColor' and 'labels' arguments to change the colors and the labels of the individuals represented on the PCA.</p>")
  mcq.plot.pca(XIC_PCA, factorToColor=c(), labels=c(), tagType="label", labelSize=4)





library(data.table)


get.proteobench <- function(pepq) {

   # sequence   ProForma  rawfile charge proteins
   #(containing "SPECIES" and separated with ";" if it is a protein group
  if ('ProForma' %in% names(pepq@proteins)) {
  }
  else {
    stop(paste("ProForma column is not present, please use at least MassChroQ version 2.4.5 to produce peptide quantification tables",sep=""))
  }
  data <- getdf(pepq)
  datamproteobench <-data[, c("sequence","ProForma", "z", "accession")]
  #datamsstats$sequence <- gsub("L","I",datamsstats$sequence)
  #datamsstats$sequence <- data$peptiniid
  colnames(datamproteobench) <- c("sequence","ProForma", "charge", "proteins")
  datamproteobench$charge <- data$z
  if ("label" %in% colnames(data)) {
    #datamproteobench$IsotopeLabelType <- data$label
    #datamproteobench$IsotopeLabelType <- str_replace(datamproteobench$IsotopeLabelType, "light", "L")
    #datamproteobench$IsotopeLabelType <- str_replace(datamproteobench$IsotopeLabelType, "heavy", "H")
    #datamproteobench$IsotopeLabelType[is.na(datamproteobench$IsotopeLabelType)] <- "L"
  }
  else {
    #datamproteobench$IsotopeLabelType <- "L"
  }

  datamproteobench$rawfile <- data$msrun
  if("areanorm" %in% colnames(data)){
    datamproteobench$area <- data$areanorm
  } else {
    datamproteobench$area <- data$area
  }
  #populate NA for missing values
  df_unique_ion <- unique(datamproteobench[c("sequence","ProForma", "charge", "proteins")])


  proteobench_conditions <- unique (datamproteobench[,c("rawfile", "proteins")])

  datamproteobench = as.data.table(datamproteobench)


  datamproteobench <- merge(cbind(pepq@metadata@injections, row=row.names(pepq@metadata@injections)), datamproteobench, by.x="row", by.y="rawfile")

  datamproteobench$row <- NULL;
  colnames(datamproteobench)[colnames(datamproteobench) == 'msrunfile'] <- 'rawfile'
  return (datamproteobench);

}


getdf <- function(object) {
	protein <- accession <- protein_description <- NULL
    temp_proteins = unique(object@proteins[,c("peptide", "protein", "accession", "protein_description")])

	shared.pep <- names(table(temp_proteins$peptide))[table(temp_proteins$peptide)>1]
	tab <- as.data.table(object@proteins[object@proteins$peptide %in% shared.pep,c("peptide", "protein", "accession", "protein_description")])
    tab <- tab[,list(protein = paste(protein, collapse=";"), accession = paste(accession, collapse=";"), protein_description = paste(protein_description, collapse=";")), by="peptide"]
	#tab <- ddply(tab, .(peptide), summarize,  protein=paste(protein, collapse=";"), accession=paste(accession, collapse=";"), protein_description=paste(protein_description, collapse=";"))
	tab <- rbind.data.frame(tab, object@proteins[!object@proteins$peptide %in% shared.pep,c("peptide", "protein", "accession", "protein_description")])

	indice <- match(object@peptides$peptide, tab$peptide)

	object@peptides$protein <- tab$protein[indice]
	object@peptides$accession <- tab$accession[indice]
	object@peptides$protein_description <- tab$protein_description[indice]
	if (nrow(object@metadata@metadata)!=0) {
		tpep <- merge(object@peptides, object@metadata@metadata, by.x="msrun", by.y="row.names")
	}

	tpep <- tpep[order(tpep$msrun,tpep$peptide),]
	colnames(tpep)[which(colnames(tpep)=="logarea")] <- "log10area"
	colnames(tpep)[which(colnames(tpep)=="lognorm")] <- "log10norm"


	if ('ProForma' %in% names(object@proteins)) {
	  tpep <- merge(tpep, object@proteins[,c("peptide","ProForma")], by.x="peptide", by.y="peptide", all.x = TRUE)
	}
	return (unique(tpep))
}

cat("<h3>writing proteobench tsv file</h3>")

df_proteobench <- get.proteobench(XIC)
write.table(df_proteobench, file = "/home/olangella/Téléchargements/demo/proteobench_export.tsv", sep = "\t", row.names = F, quote = T)
