/**
 * \file /gui/run/mcqr/mcqrrunviewng.cpp
 * \date 14/06/2023
 * \author Olivier Langella
 * \brief dialog window to run MCQR process
 */


/*******************************************************************************
 * Copyright (c) 2023 Olivier Langella
 *<Olivier.Langella@universite-paris-saclay.fr>.
 *
 * This file is part of i2MassChroQ.
 *
 *     i2MassChroQ is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     i2MassChroQ is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with i2MassChroQ.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#include "mcqrrunviewng.h"
#include "../../mainwindow.h"
#include "ui_mcqr_run_view_ng.h"
#include <QDebug>
#include <odsstream/odsdocwriter.h>
#include <odsstream/ziptsvoutputstream.h>
#include <odsstream/odsexception.h>
#include <odsstream/tsvreader.h>
#include "../../../output/mcqr/mcqrmetadataods.h"
#include <pappsomspp/core/exception/exceptionnotpossible.h>
#include <pappsomspp/core/exception/exceptionnotfound.h>
#include <pappsomspp/core/processing/uimonitor/uimonitorvoid.h>
#include "../../../input/msstats/tsvtranslator.h"


McqrRunViewNg::McqrRunViewNg(MainWindow *parent)
  : RworkflowRunViewBase(parent), ui(new Ui::McqrRunViewNg)
{
  ui->setupUi(this);

  connect(ui->widgetRprocess,
          &WidgetRprocess::stepFinished,
          this,
          &McqrRunViewNg::doStepFinished);
  ui->chooseReferenceNorm->setVisible(false);
  qDebug();
  m_rviewName = "MCQR";

  checkInstall();
}

McqrRunViewNg::~McqrRunViewNg()
{
}

void
McqrRunViewNg::setWorkingDirectoryLabel()
{
  m_mcqCborReader.setMcqrWorkingDirectory(m_workingDirectory);
  ui->wdLabel->setText(m_workingDirectory);
  QDir directory(m_workingDirectory);

  try
    {
      if(QFileInfo(directory.absoluteFilePath("metadata.ods")).exists())
        {
          try
            {
              updateMetadataFactorListView();
            }
          catch(pappso::ExceptionNotFound &not_found)
            {
            }
        }
    }
  catch(pappso::PappsoException &error)
    {
      warning(error.qwhat());
    }
}
void
McqrRunViewNg::checkInstall()
{

  Cutelee::Engine *engine_p = new Cutelee::Engine();
  auto loader = std::shared_ptr<Cutelee::FileSystemTemplateLoader>(
    new Cutelee::FileSystemTemplateLoader());
  loader->setTemplateDirs({":/templates/resources/templates/mcqr_scripts"});
  engine_p->addTemplateLoader(loader);
  Cutelee::Template rscript_template_sp =
    engine_p->loadByName("mcqr_packages_handler.R");
  Cutelee::Context empty_context;
  ui->widgetRprocess->executeOnTheRecord(
    rscript_template_sp->render(&empty_context));


  executeStep("libraries");
}
/*
void
McqrRunViewNg::doSelectMasschroqMlFile()
{

  try
    {
      QSettings settings;

      QString default_location = settings.value("path/mcqfile", "").toString();

      QString filename = QFileDialog::getOpenFileName(
        this,
        tr("select masschroqML file"),
        QDir(default_location).absolutePath(),
        tr("masschroqML files (*.masschroqml);;all files (*)"));


      if(!filename.isEmpty())
        {
          settings.setValue("path/mcqfile", QFileInfo(filename).absolutePath());

          if(m_mcqlReader.readFile(filename))
            {
              m_projectParameters = m_mcqlReader.getProjectParameters();
              executeStep("load");
            }
          else
            {

              throw pappso::PappsoException(m_mcqlReader.errorString());
            }
        }
      qDebug() << filename;
    }
  catch(pappso::PappsoException &error)
    {
      warning(
        tr("Error reading masschroqML parameter file : %1").arg(error.qwhat()));
      // QMessageBox::warning(this,
      //                  tr("Error choosing identification result files :
      //                  %1").arg(error.qwhat()), error);
    }
}
*/
void
McqrRunViewNg::doSelectMasschroqCborFile()
{

  try
    {
      QSettings settings;

      QString default_location = settings.value("path/mcqfile", "").toString();

      QString filename = QFileDialog::getOpenFileName(
        this,
        tr("select MassChroQ CBOR file"),
        QDir(default_location).absolutePath(),
        tr("MassChroQ CBOR files (*.cbor);;all files (*)"));


      if(!filename.isEmpty())
        {
          settings.setValue("path/mcqfile", QFileInfo(filename).absolutePath());

          pappso::UiMonitorVoid monitor;
          QFile f(filename);
          if(f.open(QIODevice::ReadOnly))
            {
              qDebug();
              m_mcqCborReader.readCbor(&f, monitor);
            }
          else
            {

              throw pappso::PappsoException(
                QObject::tr("failure opening file %1")
                  .arg(QFileInfo(filename).absolutePath()));
            }

          m_mcqCborReader.writePeptideProteinFiles(filename, monitor);
          m_projectParameters = m_mcqCborReader.getProjectParameters();
          executeStep("load");
          qDebug() << filename;
        }
    }
  catch(pappso::PappsoException &error)
    {
      warning(tr("Error reading MassChroQ CBOR file : %1").arg(error.qwhat()));
      // QMessageBox::warning(this,
      //                  tr("Error choosing identification result files :
      //                  %1").arg(error.qwhat()), error);
    }
}


WidgetRprocess *
McqrRunViewNg::getWidgetRprocess() const
{
  return ui->widgetRprocess;
}

void
McqrRunViewNg::doA3A2McqrDubiousDataFilter()
{
  executeStep("a3a2_mcqr_dubiousDataFilter");
}

void
McqrRunViewNg::doA3A1McqrRemoveMsrun()
{

  executeStep("a3a1_mcqr_removeMsrun");
}

void
McqrRunViewNg::doA2McqrPca()
{
  executeStep("a2a2_mcqr_pca");
}

void
McqrRunViewNg::executeStep(const QString &step)
{
  qDebug() << step;

  pappso::ProjectParam parameter(
    {pappso::ProjectParamCategory::quantification, "", QVariant()});
  parameter.name = "mcqr_version";
  parameter.value.setValue(getWidgetRprocess()->getMcqrVersion());
  m_projectParameters.setProjectParam(parameter);

  Cutelee::Engine *engine_p = new Cutelee::Engine();
  auto loader = std::shared_ptr<Cutelee::FileSystemTemplateLoader>(
    new Cutelee::FileSystemTemplateLoader());
  loader->setTemplateDirs({":/templates/resources/templates/mcqr_scripts"});
  engine_p->addTemplateLoader(loader);
  Cutelee::Template rscript_template_sp =
    engine_p->loadByName("mcqrng_analysis.R");
  Cutelee::Context context;
  context.insert("step", step);

  if(step != "libraries")
    {
      if(m_workingDirectory.isEmpty())
        {
          warning("Error : working directory is not set.");
          return;
        }
      else
        {
          if(ui->widgetRprocess->isFinished())
            {
              executeStep("libraries");
            }
          context.insert(
            "tmp_path",
            QDir(m_workingDirectory).absoluteFilePath(" ").trimmed());
          if(step == "load")
            {
              if(m_mcqCborReader.getMcqrMetadataSet()
                   .getMcqrMetadataList()
                   .size() == 0)
                {
                  warning("Error : MassChroQ CBOR file not selected.");
                  return;
                }

              context.insert("protein_tsv_file",
                             m_mcqCborReader.getProteinTsvResultFilename());

              context.insert("peptide_tsv_file",
                             m_mcqCborReader.getPeptideTsvResultFilename(
                               m_mcqCborReader.getSingleGroupId()));
            }
          else if(step == "merge_metadata")
            {
              if(!fileExists("xicraw_nometadata.rdata"))
                {
                  warning("Error : masschroqML file not selected.");
                  return;
                }

              // factors_color
              if(!getColorListString().isEmpty())
                {
                  context.insert("factors_color", getColorListString());
                }
            }


          else if(step == "a2a2_mcqr_pca")
            {
              if(!fileExists("xicraw.rdata"))
                {
                  warning("Error : metadata file not uploaded.");
                  return;
                }

              // factors_color
              if(!getColorListString().isEmpty())
                {
                  context.insert("factors_color", getColorListString());
                }
              // factors_label
              context.insert("factors_label", getLabelListString());

              //{{ factors_color }}), labels=c({{ factors_label }}
            }
          else if(step == "a3a1_mcqr_removeMsrun")
            {
              if(ui->msrunListView->getQStringList().size() == 0)
                {
                  warning("Error : choose at least one msrun to remove.");
                  return;
                }
              context.insert("msrun_list_drop",
                             ui->msrunListView->getMsrunListString());

              if(!fileExists("xicraw.rdata"))
                {
                  warning("Error : metadata file not uploaded.");
                  return;
                }
            }

          else if(step == "a3a2_mcqr_dubiousDataFilter")
            {

              context.insert("cutoff_rt", ui->rt_cutoff_spin->value());
              context.insert("cutoff_peaks", ui->peaks_cutoff_spin->value());


              parameter.name = "mcqr_cutoff_rt";
              parameter.value.setValue(ui->rt_cutoff_spin->value());
              m_projectParameters.setProjectParam(parameter);


              parameter.name = "mcqr_cutoff_peaks";
              parameter.value.setValue(ui->peaks_cutoff_spin->value());
              m_projectParameters.setProjectParam(parameter);

              if(!fileExists("xicraw.rdata"))
                {
                  warning("Error : metadata file not uploaded.");
                  return;
                }
            }
          else if(step == "a4a1_mcqr_normalization")
            {
              if(!fileExists("xicraw.rdata"))
                {
                  warning("Error : metadata file not uploaded.");
                  return;
                }
              context.insert("norm_method",
                             ui->normMethodComboBox->currentText());
              parameter.name = "mcqr_normalization_method";
              parameter.value.setValue(ui->normMethodComboBox->currentText());
              m_projectParameters.setProjectParam(parameter);
              // factors_color
              if(!getColorListString().isEmpty())
                {
                  context.insert("factors_color", getColorListString());
                }
              // factors_label
              context.insert("factors_label", getLabelListString());

              if(ui->chooseReferenceNorm->isVisible())
                {
                  context.insert("msrun_reference",
                                 ui->msrunReferenceComboBox->getMsrunId());

                  parameter.name = "mcqr_normalization_msrun_reference";
                  parameter.value.setValue(
                    ui->normMethodComboBox->currentText());
                  m_projectParameters.setProjectParam(parameter);
                }
              else
                {
                  context.insert("msrun_reference", "");
                }
            }
          else if(step == "a4a1_proteobench")
            {
              qDebug();
              if(!fileExists("a4a1_backup_xic.rdata"))
                {
                  warning(
                    "Error : process with Nomalisation and PCA before "
                    "proteobench export.");
                  return;
                }

              context.insert("step", "export_current_pepq_in_proteobench");
              context.insert("pepq_rdatafile", "xic.rdata");
            }
          else if(step == "a4a2_mcqr_norm_remove_msrun")
            {
              if(!fileExists("a4a1_backup_xic.rdata"))
                {
                  warning("Error : missing normalisation step.");
                  return;
                }
              if(ui->msrunRemoveAfterNormListview->getQStringList().size() == 0)
                {
                  warning("Error : choose at least one msrun to remove.");
                  return;
                }
              context.insert(
                "msrun_list_drop",
                ui->msrunRemoveAfterNormListview->getMsrunListString());

              if(!fileExists("xicraw.rdata"))
                {
                  warning("Error : metadata file not uploaded.");
                  return;
                }
            }
          else if(step == "a5a1_mcqr_filter_shared")
            {

              qDebug() << step;
              if(!fileExists("xic.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }
            }
          else if(step == "a5a2_mcqr_filter_unreproducible")
            {

              qDebug() << step;
              if(!fileExists("xic.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }

              //  nb_factor_levels
              QStringList level_list = ui->factorListView->getLevels();
              level_list.removeDuplicates();
              qDebug() << "level_list.size()=" << level_list.size() << " "
                       << level_list.join(" ");
              context.insert("nb_factor_levels", (level_list.size()));
              // percent_na
              context.insert("percent_na", ui->max_na_percent_spin->value());
              // drop_method
              context.insert("drop_method",
                             ui->drop_method_combo->currentText());
              // factors_list
              context.insert("factors_list", getFactorListString());
              // corr_cutoff
              context.insert("corr_cutoff", ui->corr_cutoff_spin->value());
              // n_prot_corr
              context.insert("n_prot_corr", ui->nb_prot_corr_spin->value());
              // filter_imputed
              context.insert(
                "filter_imputed",
                toRboolean(ui->filter_imputed_switch->getSwitchValue()));
              // filter_log
              context.insert(
                "filter_log",
                toRboolean(ui->filter_log_switch->getSwitchValue()));
            }
          else if(step == "a6a1_mcqr_filter_uncorrelated")
            {
              qDebug() << step;
              if(!fileExists("xic.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }

              QStringList level_list = ui->factorListView->getLevels();
              level_list.removeDuplicates();
              if(level_list.size() < 5)
                {
                  warning(
                    QString("Unable to perform correlation. You need at least "
                            "5 levels from the chosen factors or combination "
                            "of factors.\nCurrent levels are : \"%1\"")
                      .arg(level_list.join("\", \"")));
                  return;
                }
              // factors_list
              context.insert("factors_list", getFactorListString());
              // cor_cutoff
              context.insert("cor_cutoff", ui->drop_corr_cutoff_spin->value());
            }
          // a6a2_mcqr_filter_few_peptides
          else if(step == "a6a2_mcqr_filter_few_peptides")
            {
              qDebug() << step;
              if(!fileExists("xic.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }
              // nb_pep
              context.insert("nb_pep", ui->nb_peptides_cutoff_spin->value());
            }
          // a7_mcqr_imputation
          else if(step == "a7_mcqr_imputation")
            {
              qDebug() << step;
              if(!fileExists("xic.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }
              // imputation_method
              context.insert("imputation_method",
                             ui->imputation_method_combo->currentText());
              // abundance_method
              context.insert("abundance_method",
                             ui->abundance_method_combo->currentText());
              // factors_list
              context.insert("factors_list", getFactorListString());
              // factors_color
              context.insert("factors_color", getColorListString());
              // factors_label
              context.insert("factors_label", getLabelListString());
            }
          // a8_mcqr_protein_heatmap
          else if(step == "a8_mcqr_protein_heatmap")
            {
              qDebug() << step;
              if(!fileExists("xicab.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }

              if(getFactorListString().isEmpty())
                {
                  warning("Error : please select at least one factor.");
                  return;
                }
              // factors_list
              context.insert("factors_list", getFactorListString());
              // factors_color
              context.insert("factors_color", getColorListString());
              // distance_fun
              context.insert("distance_fun",
                             ui->distfun_combobox->currentText());
              // agg_method
              context.insert("agg_method",
                             ui->agg_method_combobox->currentText());
            }

          else if(step == "a9_mcqr_protein_cluster")
            {
              qDebug() << step;
              if(!fileExists("xicab.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }

              // factor_list
              context.insert("factor_list", getFactorListString());
              // nb_cluster
              context.insert("nb_cluster", ui->cluster_spin->value());
              // cluster_method
              context.insert("cluster_method",
                             ui->cluster_method_comboBox->currentText());
            }
          else if(step == "b10_mcqr_protein_anova")
            {
              qDebug() << step;
              if(!fileExists("xicab.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }


              if(getFactorListString().isEmpty())
                {
                  warning("Error : please select at least one factor.");
                  return;
                }
              // factor_list
              context.insert("factors_list", getFactorListString());
              // fc_cutoff
              context.insert("fc_cutoff", ui->anova_fc_cutoff_spin->value());
              // inter_bool
              context.insert(
                "inter_bool",
                toRboolean(ui->interaction_anova_switch->getSwitchValue()));
            }

          else if(step == "b11_mcqr_plot_protein_abundance")
            {
              qDebug() << step;
              if(getFactorListString().size() == 0)
                {
                  warning("Error : you have to choose at least one factor.");
                  return;
                }
              if(!fileExists("xicab_anova.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }

              // factors_list
              context.insert("factors_string_list",
                             ui->factorListView->getQStringList());
              // factors_list_join
              context.insert("factors_list_join", getFactorListString());
              // padjust
              context.insert("padjust",
                             toRboolean(ui->padjust_switch->getSwitchValue()));
              // alpha
              context.insert("alpha", ui->alpha_spin->value());
              // factors_color
              context.insert("factors_color", getColorListString());
            }

          else if(step == "b12_mcqr_protein_abundance_fold_change")
            {
              qDebug() << step;
              if(!fileExists("xicab_selected.rdata"))
                {
                  warning("Error : missing previous steps.");
                  return;
                }
              // fc_factor
              context.insert("fc_factor",
                             ui->factorFoldChangeCombobox->currentText());
              // num
              context.insert("num",
                             ui->numeratorFoldChangeCombobox->currentText());
              // denom
              context.insert("denom",
                             ui->denominatorFoldChangeCombobox->currentText());
            }
          else
            {
              throw pappso::PappsoException(
                tr("MCQR step %1 does not exists").arg(step));
            }
        }
    }
  try
    {
      ui->widgetRprocess->executeStepOnTheRecord(
        step, rscript_template_sp->render(&context));
    }
  catch(pappso::ExceptionNotPossible &error)
    {
      warning(error.qwhat());
    }
}

void
McqrRunViewNg::doA4A1McqrNormalization()
{
  executeStep("a4a1_mcqr_normalization");
}

void
McqrRunViewNg::doA4A1proteobench()
{
  qDebug();

  removeFile("proteobench_export.tsv");
  executeStep("a4a1_proteobench"); // it calls
                                   // export_current_pepq_in_proteobench
}


void
McqrRunViewNg::doStepFinished(QString step_finished)
{
  qDebug() << step_finished;
  if(step_finished == "a4a1_proteobench")
    {
      writeProteobenchOds("proteobench_export.tsv", "ProteoBench table");
    }
}

void
McqrRunViewNg::doA4A2McqrNormRemoveMsrun()
{
  executeStep("a4a2_mcqr_norm_remove_msrun");
}


void
McqrRunViewNg::doGetMetadataTemplateFile()
{

  if(m_mcqCborReader.isOk() == false)
    {
      warning("Error : select your MassChroQ CBOR file before proceeding.");
      return;
    }
  // QString q_id                 = m_mcqlReader.getSingleQid();
  QString group_id             = m_mcqCborReader.getSingleGroupId();
  McqrMetadataSet metadata_set = m_mcqCborReader.getMcqrMetadataSet();

  metadata_set.addColumn("Condition");
  metadata_set.addColumn("BioReplicate");


  QSettings settings;
  QString metadata_template_path =
    QFileDialog::getSaveFileName(this,
                                 tr("Save the template"),
                                 "metadata_template.ods",
                                 tr("Spreadsheet (*.ods)"));
  if(!metadata_template_path.isEmpty())
    {
      try
        {
          qDebug() << metadata_template_path;
          CalcWriterInterface *p_writer =
            new OdsDocWriter(metadata_template_path);
          qDebug();
          McqrMetadataOds mcqr_metadata_ods(p_writer, metadata_set);

          qDebug();
          p_writer->close();
          settings.setValue("mcqr/metadata_path", metadata_template_path);

          launchDesktopSoftwareOnFile(metadata_template_path);
          qDebug();
        }
      catch(OdsException &error)
        {
          qDebug() << tr("error while writing metadata template:\n%1")
                        .arg(error.qwhat());
        }
      catch(pappso::PappsoException &error)
        {
          qDebug() << tr("error while downloading the metadata template:\n%1")
                        .arg(error.qwhat());
        }
    }
}

void
McqrRunViewNg::doUploadMetadataFile()
{

  QSettings settings;

  QString metadata_path = QFileDialog::getOpenFileName(
    this,
    tr("select the metadata file"),
    settings.value("mcqr/metadata_path", "/").toString(),
    tr("Spreadsheet (*.ods)"));
  qDebug() << QFileInfo(metadata_path).absoluteFilePath();
  if(!metadata_path.isEmpty())
    {
      try
        {
          QDir directory(m_workingDirectory);

          qDebug() << directory.absoluteFilePath("metadata.ods");
          if(directory.absoluteFilePath("metadata.ods") ==
             QFileInfo(metadata_path).absoluteFilePath())
            {
              throw pappso::PappsoException(
                QObject::tr("Unable to read metadata file : %1\n Please "
                            "prepare your metadata file in an other directory")
                  .arg(directory.absoluteFilePath("metadata.ods")));
            }

          if(QFileInfo(directory.absoluteFilePath("metadata.ods")).exists())
            {

              if(QFile::remove(directory.absoluteFilePath("metadata.ods")))
                {
                  // OK
                }
              else
                {
                  throw pappso::PappsoException(
                    QObject::tr("Unable to remove existing file : %1\n Please "
                                "check for file system permissions")
                      .arg(directory.absoluteFilePath("metadata.ods")));
                }
            }
          if(QFile::copy(metadata_path,
                         directory.absoluteFilePath("metadata.ods")))
            {
              // OK
            }
          else
            {
              throw pappso::PappsoException(
                QObject::tr("Unable write file : %1\nPlease check for file "
                            "system permissions")
                  .arg(directory.absoluteFilePath("metadata.ods")));
            }


          try
            {
              updateMetadataFactorListView();
            }
          catch(pappso::ExceptionNotFound &not_found)
            {
            }
          executeStep("merge_metadata");
          QFile::remove(directory.absoluteFilePath("xic.rdata"));
        }
      catch(pappso::PappsoException &error)
        {
          warning(QObject::tr("Cannot load metadata ods file: %1")
                    .arg(error.qwhat()));
        }
      qDebug();
    }
}

void
McqrRunViewNg::updateMetadataFactorListView()
{
  m_metadataSet = readMetadata();
  ui->colorListView->setMcqrMetadataSet(m_metadataSet);
  ui->factorListView->setMcqrMetadataSet(m_metadataSet);
  ui->labelListView->setMcqrMetadataSet(m_metadataSet);
  ui->factorFoldChangeCombobox->setMcqrMetadataSet(m_metadataSet);
  ui->msrunListView->setMcqrMetadataSet(m_metadataSet);
  ui->msrunReferenceComboBox->setMcqrMetadataSet(m_metadataSet);
  ui->msrunRemoveAfterNormListview->setMcqrMetadataSet(m_metadataSet);
  // ui->numeratorFoldChangeCombobox->setMcqrMetadataSet(metadata_set);
  // ui->denominatorFoldChangeCombobox->setMcqrMetadataSet(metadata_set);
  doFactorProteinFoldSelected(ui->factorFoldChangeCombobox->currentText());
}

void
McqrRunViewNg::doFactorProteinFoldSelected(QString factor)
{
  qDebug() << factor;
  ui->numeratorFoldChangeCombobox->setMcqrMetadataSetFactorValues(m_metadataSet,
                                                                  factor);
  ui->denominatorFoldChangeCombobox->setMcqrMetadataSetFactorValues(
    m_metadataSet, factor);
}


void
McqrRunViewNg::doA5A1FilterSharedPeptides()
{
  qDebug();
  executeStep("a5a1_mcqr_filter_shared");
}

void
McqrRunViewNg::doA5A2FilterUnreproduciblePeptides()
{
  qDebug();
  executeStep("a5a2_mcqr_filter_unreproducible");
}


void
McqrRunViewNg::doA6A1filterUncorrelatedPeptides()
{
  qDebug();
  executeStep("a6a1_mcqr_filter_uncorrelated");
}

void
McqrRunViewNg::doA6A2filterProteinWithFewPeptides()
{
  qDebug();
  executeStep("a6a2_mcqr_filter_few_peptides");
}

void
McqrRunViewNg::doA7imputation()
{
  qDebug();
  executeStep("a7_mcqr_imputation");
}

void
McqrRunViewNg::doA8proteinHeatmap()
{
  executeStep("a8_mcqr_protein_heatmap");
}

void
McqrRunViewNg::doA9proteinClustering()
{
  executeStep("a9_mcqr_protein_cluster");
}


void
McqrRunViewNg::doB10proteinAnova()
{
  executeStep("b10_mcqr_protein_anova");
}

void
McqrRunViewNg::doB11plotProteinAbundance()
{
  executeStep("b11_mcqr_plot_protein_abundance");
}


void
McqrRunViewNg::doB12proteinAbundanceFoldChange()
{
  executeStep("b12_mcqr_protein_abundance_fold_change");
}


QString
McqrRunViewNg::getColorListString() const
{
  QString color_list;
  if(ui->colorListView->getQStringList().size() > 0)
    {
      color_list = QString("\"%1\"").arg(
        ui->colorListView->getQStringList().join("\",\""));
    }
  return color_list;
}

QString
McqrRunViewNg::getFactorListString() const
{
  QString color_list;
  if(ui->factorListView->getQStringList().size() > 0)
    {
      color_list = QString("\"%1\"").arg(
        ui->factorListView->getQStringList().join("\",\""));
    }
  return color_list;
}

QString
McqrRunViewNg::getLabelListString() const
{
  QString color_list;
  if(ui->labelListView->getQStringList().size() > 0)
    {
      color_list = QString("\"%1\"").arg(
        ui->labelListView->getQStringList().join("\",\""));
    }
  return color_list;
}

void
McqrRunViewNg::doNormalisationMethodChanged(QString method)
{
  qDebug();
  ui->chooseReferenceNorm->setVisible(false);
  if(method.startsWith("diff.median"))
    {
      ui->chooseReferenceNorm->setVisible(true);
    }
}


void
McqrRunViewNg::writeProteobenchOds(const QString &tsv_file,
                                   const QString &file_description)
{
  if(!fileExists(tsv_file))
    {
      warning("Error : tsv_file is empty.");
      return;
    }

  QString project_name;
  if(mp_main->getProjectSp().get() != nullptr)
    {
      project_name = mp_main->getProjectSp().get()->getProjectName();
    }

  QSettings settings;
  QString ods_export = QFileDialog::getSaveFileName(
    this,
    tr("Save %1 table").arg(file_description),
    QDir(settings.value("path/export_ods", "").toString())
      .absoluteFilePath(project_name.append(".zip")),
    tr("Zip archive (*.zip);;All files (*.*)"));
  if(!ods_export.isEmpty())
    {
      try
        {
          qDebug() << ods_export;
          CalcWriterInterface *p_writer = new ZipTsvOutputStream(ods_export);
          qDebug();
          pappso::ProjectParameters params;

          if(mp_main->getProjectSp().get() != nullptr)
            {
              params = mp_main->getProjectSp().get()->getProjectParameters();
            }

          params.setProjectParam({pappso::ProjectParamCategory::quantification,
                                  "mcq_mbr",
                                  QVariant(true)});

          params.merge(m_projectParameters);

          params.writeParameters(*p_writer);

          // p_writer->writeSheet("metadata");
          TsvTranslator tsv_translator(p_writer);

          QFile file(filePath(tsv_file));

          TsvReader reader(tsv_translator);

          reader.parse(file);
          qDebug();
          p_writer->close();

          launchDesktopSoftwareOnFile(ods_export);
          qDebug();
        }
      catch(OdsException &error)
        {
          qDebug() << tr("error while writing %1 table:\n%2")
                        .arg(file_description)
                        .arg(error.qwhat());
        }
      catch(pappso::PappsoException &error)
        {
          qDebug() << tr("error while downloading %1 table:\n%2")
                        .arg(file_description)
                        .arg(error.qwhat());
        }
    }
}
