/**
 * \file gui/mcqr_run_view/mcqr_sds_xic_widget/mcqrsdsxicwidget.cpp
 * \date 30/06/2021
 * \author Thomas Renne
 * \brief widget to run the XIC part from SDS script from MCQR
 */

/*******************************************************************************
 * Copyright (c) 2021 Thomas Renne <thomas.renne@e.email>.
 *
 * This file is part of XTPcpp.
 *
 *     XTPcpp 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.
 *
 *     XTPcpp 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 XTPcpp.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contributors:
 *     Thomas Renne <thomas.renne@e.email> - initial API and
 *implementation
 ******************************************************************************/

#include "mcqrsdsxicwidget.h"
#include "ui_mcqr_sds_xic_widget.h"

#include <QMessageBox>
#include <pappsomspp/pappsoexception.h>
#include <pappsomspp/utils.h>

#include "../mcqrrunview.h"

McqrSdsXicWidget::McqrSdsXicWidget(McqrRunView *mcqr_window,
                                   const McqrExperimentSp &p_mcqr_experiment)
  : McqrParamWidget(mcqr_window, p_mcqr_experiment),
    ui(new Ui::McqrSdsXicWidget)
{
  ui->setupUi(this);

  mp_factorsColorModel = new QStandardItemModel(ui->factors_color_view);
  mp_factorsLabelModel = new QStandardItemModel(ui->factors_label_view);
  mp_factorsListModel  = new QStandardItemModel(ui->factors_list_view);

  disableFutureStepsInToolBox();
  addFactorsToListViews();
  initGrantleeEngine();
  m_mcqrLoadDataMode = p_mcqr_experiment.get()->getMcqrLoadDataMode();
}

McqrSdsXicWidget::~McqrSdsXicWidget()
{
}

void
McqrSdsXicWidget::disableFutureStepsInToolBox()
{

  qDebug();
  int number_of_pages = ui->toolBox->count();
  for(int i = 1; i < number_of_pages; i++)
    {
      ui->toolBox->setItemEnabled(i, false);
    }

  qDebug();
}

void
McqrSdsXicWidget::addFactorsToListViews()
{

  qDebug();
  int i = 0;
  for(QString factor : getMcqrExperimentSpLoaded().get()->getmetadataColumns())
    {
      QStandardItem *new_factor_color = new QStandardItem(factor);
      new_factor_color->setCheckable(true);
      new_factor_color->setData(Qt::Unchecked, Qt::CheckStateRole);
      mp_factorsColorModel->setItem(i, new_factor_color);

      QStandardItem *new_factor_label = new QStandardItem(factor);
      new_factor_label->setCheckable(true);
      new_factor_label->setData(Qt::Unchecked, Qt::CheckStateRole);
      mp_factorsLabelModel->setItem(i, new_factor_label);

      QStandardItem *new_factor_item = new QStandardItem(factor);
      new_factor_item->setCheckable(true);
      new_factor_item->setData(Qt::Unchecked, Qt::CheckStateRole);
      mp_factorsListModel->setItem(i, new_factor_item);

      i++;
    }
  ui->factors_color_view->setModel(mp_factorsColorModel);
  ui->factors_label_view->setModel(mp_factorsLabelModel);
  ui->factors_list_view->setModel(mp_factorsListModel);

  ui->factors_list_widget->setVisible(false);
  ui->factors_label_widget->setVisible(false);
  ui->toolBox->adjustSize();

  qDebug();
}

void
McqrSdsXicWidget::changeToolBoxHeight(int tab_selected)
{

  qDebug();
  ui->toolBox->adjustSize();
  ui->scrollAreaWidgetContents->updateGeometry();
  ui->scrollArea->update();

  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      mp_factorsListModel->item(i, 0)->setCheckState(Qt::Unchecked);
      mp_factorsLabelModel->item(i, 0)->setCheckState(Qt::Unchecked);
      mp_factorsColorModel->item(i, 0)->setCheckState(Qt::Unchecked);
    }
  switch(tab_selected)
    {
      case(int)SdsXicAnalysisStep::quality_xic:
        ui->factors_color_widget->setVisible(true);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(false);
        break;
      case(int)SdsXicAnalysisStep::filtering_data:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(false);
        break;
      case(int)SdsXicAnalysisStep::reconstituting_tracks:
        ui->factors_color_widget->setVisible(true);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::normalise:
        ui->factors_color_widget->setVisible(true);
        ui->factors_label_widget->setVisible(true);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::filtering_shared:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::filtering_uncorrelated:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::imputing:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::heatmap:
        ui->factors_color_widget->setVisible(true);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::protein_clustering:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::anova:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::protein_abundance:
        ui->factors_color_widget->setVisible(true);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      case(int)SdsXicAnalysisStep::protein_fc_abundance:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(true);
        break;
      default:
        ui->factors_color_widget->setVisible(false);
        ui->factors_label_widget->setVisible(false);
        ui->factors_list_widget->setVisible(false);
        break;
    }

  qDebug();
}

void
McqrSdsXicWidget::initGrantleeEngine()
{

  qDebug();
  mp_grantleeEngine = new Grantlee::Engine();
  auto loader = QSharedPointer<Grantlee::FileSystemTemplateLoader>::create();
  loader->setTemplateDirs({":/templates/resources/templates/mcqr_scripts"});
  mp_grantleeEngine->addTemplateLoader(loader);

  if(getMcqrExperimentSpLoaded().get()->getMcqrLoadDataMode() ==
     McqrLoadDataMode::fraction)
    {
      // if (getMcqrExperimentLoaded()
      msp_rscriptTemplate =
        mp_grantleeEngine->loadByName("mcqr_sds_xic_analysis.R");
      if(!msp_rscriptTemplate->errorString().isEmpty())
        {
          throw pappso::PappsoException(
            QObject::tr(
              "An error happened during the template file loading :\n%1")
              .arg(msp_rscriptTemplate->errorString()));
        }
    }
  else if(getMcqrExperimentSpLoaded().get()->getMcqrLoadDataMode() ==
          McqrLoadDataMode::basic)
    {
      // if (getMcqrExperimentLoaded()
      msp_rscriptTemplate =
        mp_grantleeEngine->loadByName("mcqr_basic_xic_analysis.R");
      if(!msp_rscriptTemplate->errorString().isEmpty())
        {
          throw pappso::PappsoException(
            QObject::tr(
              "An error happened during the template file loading :\n%1")
              .arg(msp_rscriptTemplate->errorString()));
        }
    }
  else
    {
      throw pappso::PappsoException(
        QObject::tr("currently, only fraction  experiment can be run inside "
                    "X!TandemPipeline"));
    }

  qDebug();
}

void
McqrSdsXicWidget::changeStepAfterEndTag(QString end_name)
{

  qDebug();
  if(end_name == "MCQREnd: quality_xic")
    {
      qDebug() << "Configure filtering tab";
      configureFilteringTab();
    }
  else if(end_name == "MCQREnd: filtering_data")
    {
      if(m_mcqrLoadDataMode == McqrLoadDataMode::basic)
        {
          configureNormaliseTab();
        }
      else
        {
          configureReconstitutingTab();
        }
    }
  else if(end_name == "MCQREnd: reconstiting_fraction")
    {
      configureNormaliseTab();
    }
  else if(end_name == "MCQREnd: normalizing_peptides")
    {
      ui->toolBox->setItemEnabled(4, true);
      ui->toolBox->setCurrentIndex(4);
      ui->toolBox->update();
      ui->filter_log_switch->setSwitchValue(true);
    }
  else if(end_name == "MCQREnd: filtering_shared")
    {
      ui->toolBox->setItemEnabled(5, true);
      ui->toolBox->setCurrentIndex(5);
      ui->toolBox->update();
    }
  else if(end_name == "MCQREnd: filtering_uncorrelated")
    {
      ui->toolBox->setItemEnabled(6, true);
      ui->toolBox->setCurrentIndex(6);
      ui->toolBox->update();
    }
  else if(end_name == "MCQREnd: imputing")
    {
      ui->toolBox->setItemEnabled(7, true);
      ui->toolBox->setCurrentIndex(7);
      ui->toolBox->update();
    }
  else if(end_name == "MCQREnd: heatmap")
    {
      ui->toolBox->setItemEnabled(8, true);
      ui->toolBox->setCurrentIndex(8);
      ui->toolBox->update();
    }
  else if(end_name == "MCQREnd: protein_clustering")
    {
      ui->toolBox->setItemEnabled(9, true);
      ui->toolBox->setCurrentIndex(9);
      ui->toolBox->update();
    }
  else if(end_name == "MCQREnd: anova")
    {
      ui->toolBox->setItemEnabled(10, true);
      ui->toolBox->setCurrentIndex(10);
      ui->toolBox->update();
    }
  else if(end_name == "MCQREnd: protein_abundance")
    {
      configureFcFactorList();
      ui->toolBox->setItemEnabled(11, true);
      ui->toolBox->setCurrentIndex(11);
      ui->toolBox->update();
    }

  qDebug();
}

void
McqrSdsXicWidget::runQualityCheckingXic()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::quality_xic;

  QStringList factors_color;
  for(int i = 0; i < mp_factorsColorModel->rowCount(); i++)
    {
      QStandardItem *color_item = mp_factorsColorModel->item(i, 0);
      if(color_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_color << color_item->text();
        }
    }

  MsRunAlignmentGroupSp msrun_alignment_group_sp =
    getMcqrExperimentSpLoaded().get()->getAlignmentGroupLinkedToExperiment();


  QString xic_directory_path =
    msrun_alignment_group_sp.get()->getMassChroqmlResultTsvDirectoryPath();
  if(factors_color.size() == 0)
    {
      QMessageBox::warning(this,
                           tr("Parameter selection error"),
                           tr("You have to select at least one factor in the "
                              "factor to color list"));
    }
  else
    {
      Grantlee::Context grantlee_context;
      grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
      grantlee_context.insert(
        "mcqr_working_directory",
        QDir(getMcqrExperimentSpLoaded().get()->getMcqrWorkingDirectory())
          .path());
      grantlee_context.insert(
        "metadata_ods_path",
        getMcqrExperimentSpLoaded().get()->getMetadataOdsFilePath());
      grantlee_context.insert("xic_directory", xic_directory_path);
      grantlee_context.insert("rt_interval", ui->rt_interval_spin->value());
      grantlee_context.insert("upper_x_axis", ui->upper_x_axis_spin->value());
      grantlee_context.insert("tmp_path", getOutputTmpPath());
      grantlee_context.insert("factors_color",
                              transformQStringListInRListFormat(factors_color));
      grantlee_context.insert("sds_page",
                              ui->sds_page_switch->getSwitchValue());


      getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
        "quality_xic", msp_rscriptTemplate->render(&grantlee_context));
    }
  qDebug();
}

void
McqrSdsXicWidget::runFilteringDubiousData()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::filtering_data;

  QStringList levels;
  for(int i = 0; i < mp_factorLevelsToRemove->rowCount(); i++)
    {
      QStandardItem *level_item = mp_factorLevelsToRemove->item(i, 0);
      if(level_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          levels << level_item->text();
        }
    }

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("factor_drop",
                          ui->factor_remove_combo->currentText());
  grantlee_context.insert("levels_drop",
                          transformQStringListInRListFormat(levels));
  grantlee_context.insert("cutoff_rt", ui->rt_cutoff_spin->value());
  grantlee_context.insert(
    "fraction_rt",
    pappso::Utils::booleanToString(ui->rt_fraction_switch->getSwitchValue()));
  grantlee_context.insert("cutoff_peaks", ui->peaks_cutoff_spin->value());
  grantlee_context.insert(
    "fraction_peaks",
    pappso::Utils::booleanToString(ui->peak_fraction_switch->getSwitchValue()));

  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "filtering_data", msp_rscriptTemplate->render(&grantlee_context));
  qDebug();
}

void
McqrSdsXicWidget::runReconstitutingTracks()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::reconstituting_tracks;

  QStringList factors_color;
  QStringList factors_list;
  for(int i = 0; i < mp_factorsColorModel->rowCount(); i++)
    {
      QStandardItem *color_item = mp_factorsColorModel->item(i, 0);
      if(color_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_color << color_item->text();
        }
      QStandardItem *factor_item = mp_factorsListModel->item(i, 0);
      if(factor_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << factor_item->text();
        }
    }

  if(factors_color.size() == 0)
    {
      // TODO Add factor_list when the mcq.plot.peptide.intensity function works
      QMessageBox::warning(this,
                           tr("Parameter selection error"),
                           tr("You have to select at least one factor in the "
                              "factor to color list"));
    }
  else
    {
      Grantlee::Context grantlee_context;
      grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
      grantlee_context.insert("tmp_path", getOutputTmpPath());
      grantlee_context.insert("factor_list",
                              transformQStringListInRListFormat(factors_list));
      grantlee_context.insert("factor_color",
                              transformQStringListInRListFormat(factors_color));
      grantlee_context.insert("r_cutoff", ui->correlation_spin->value());
      grantlee_context.insert(
        "show_imputed",
        pappso::Utils::booleanToString(ui->imputed_switch->getSwitchValue()));
      grantlee_context.insert("n_prot", ui->nb_prot_spin->value());
      grantlee_context.insert(
        "log",
        pappso::Utils::booleanToString(ui->log_switch->getSwitchValue()));
      grantlee_context.insert(
        "scale",
        pappso::Utils::booleanToString(ui->scale_switch->getSwitchValue()));
      grantlee_context.insert("track_level",
                              ui->track_ref_combobox->currentText());


      getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
        "reconstituting_tracks",
        msp_rscriptTemplate->render(&grantlee_context));
    }

  qDebug();
}

void
McqrSdsXicWidget::runNormaliseIntensities()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::normalise;

  QStringList factors_color;
  QStringList factors_label;
  QStringList factors_list;
  for(int i = 0; i < mp_factorsColorModel->rowCount(); i++)
    {
      QStandardItem *color_item = mp_factorsColorModel->item(i, 0);
      if(color_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_color << color_item->text();
        }
      QStandardItem *label_item = mp_factorsLabelModel->item(i, 0);
      if(label_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_label << label_item->text();
        }
      QStandardItem *factor_item = mp_factorsLabelModel->item(i, 0);
      if(factor_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << factor_item->text();
        }
    }

  if(factors_color.size() == 0 || factors_label.size() == 0 ||
     factors_list.size() == 0)
    {
      QMessageBox::warning(
        this,
        tr("Parameter selection error"),
        tr("You have to select at least one factor in the "
           "factor to color list and one in the factor as label list"));
    }
  else
    {
      Grantlee::Context grantlee_context;
      grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
      grantlee_context.insert("tmp_path", getOutputTmpPath());
      grantlee_context.insert("factors_label",
                              transformQStringListInRListFormat(factors_label));
      grantlee_context.insert("factors_color",
                              transformQStringListInRListFormat(factors_color));
      grantlee_context.insert("factors_list",
                              transformQStringListInRListFormat(factors_list));
      grantlee_context.insert("track_ref",
                              ui->norm_ref_track_combo->currentText());
      grantlee_context.insert("norm_method",
                              ui->norm_method_combo->currentText());

      getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
        "normalise", msp_rscriptTemplate->render(&grantlee_context));
    }
  qDebug();
}

void
McqrSdsXicWidget::runFilteringSharedPeptides()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::filtering_shared;

  QStringList factors_list;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
    }
  if(factors_list.size() == 0)
    {
      QMessageBox::warning(this,
                           tr("Parameter selection error"),
                           tr("You have to select at least one factor in the "
                              "factor list"));
    }
  else
    {
      Grantlee::Context grantlee_context;
      grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
      grantlee_context.insert("tmp_path", getOutputTmpPath());
      grantlee_context.insert("factors_list",
                              transformQStringListInRListFormat(factors_list));
      grantlee_context.insert("drop_method",
                              ui->drop_method_combo->currentText());
      grantlee_context.insert("percent_na", ui->max_na_percent_spin->value());
      grantlee_context.insert("corr_cutoff", ui->corr_cutoff_spin->value());
      grantlee_context.insert("n_prot_corr", ui->nb_prot_corr_spin->value());


      getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
        "filtering_shared", msp_rscriptTemplate->render(&grantlee_context));
    }
  qDebug();
}

void
McqrSdsXicWidget::runFilteringUncorrelatedPeptides()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::filtering_uncorrelated;

  QStringList factors_list;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
    }
  if(factors_list.size() == 0)
    {
      QMessageBox::warning(this,
                           tr("Parameter selection error"),
                           tr("You have to select at least one factor in the "
                              "factor list"));
    }
  else
    {
      Grantlee::Context grantlee_context;
      grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
      grantlee_context.insert("tmp_path", getOutputTmpPath());
      grantlee_context.insert("factors_list",
                              transformQStringListInRListFormat(factors_list));
      grantlee_context.insert("corr_cutoff", ui->corr_cutoff_spin->value());
      grantlee_context.insert("nb_pep", ui->nb_peptides_cutoff_spin->value());


      getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
        "filtering_uncorrelated",
        msp_rscriptTemplate->render(&grantlee_context));
    }
  qDebug();
}

void
McqrSdsXicWidget::runImputingPeptidesProteins()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::imputing;

  QStringList factors_list;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
    }

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("factor_list_concat",
                          transformQStringListInRListFormat(factors_list));
  grantlee_context.insert("imputation_method",
                          ui->imputation_method_combo->currentText());
  grantlee_context.insert("abundance_method",
                          ui->abundance_method_combo->currentText());


  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "imputing", msp_rscriptTemplate->render(&grantlee_context));
  qDebug();
}

void
McqrSdsXicWidget::runHeatMapProteinAbundance()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::heatmap;

  QStringList factors_list;
  QStringList factors_color;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
      QStandardItem *color_item = mp_factorsColorModel->item(i, 0);
      if(color_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_color << color_item->text();
        }
    }

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("tmp_path", getOutputTmpPath());
  grantlee_context.insert("factors_list",
                          transformQStringListInRListFormat(factors_list));
  grantlee_context.insert("factors_color",
                          transformQStringListInRListFormat(factors_color));
  grantlee_context.insert("distance_fun", ui->distfun_combobox->currentText());
  grantlee_context.insert("agg_method", ui->agg_method_combobox->currentText());

  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "heatmap", msp_rscriptTemplate->render(&grantlee_context));
  qDebug();
}

void
McqrSdsXicWidget::runProteinClustering()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::protein_clustering;

  QStringList factors_list;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
    }

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("tmp_path", getOutputTmpPath());
  grantlee_context.insert("factors_list",
                          transformQStringListInRListFormat(factors_list));
  grantlee_context.insert("nb_cluster", ui->cluster_spin->value());

  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "protein_clustering", msp_rscriptTemplate->render(&grantlee_context));

  qDebug();
}

void
McqrSdsXicWidget::runProteinAnova()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::anova;

  QStringList factors_list;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
    }

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("tmp_path", getOutputTmpPath());
  grantlee_context.insert("factors_list",
                          transformQStringListInRListFormat(factors_list));
  grantlee_context.insert("fc_cutoff", ui->anova_fc_cutoff_spin->value());
  grantlee_context.insert("inter_bool",
                          pappso::Utils::booleanToString(
                            ui->interaction_anova_switch->getSwitchValue()));

  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "anova", msp_rscriptTemplate->render(&grantlee_context));
  qDebug();
}

void
McqrSdsXicWidget::runProteinAbundance()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::protein_abundance;

  QStringList factors_list;
  QStringList factors_color;
  for(int i = 0; i < mp_factorsListModel->rowCount(); i++)
    {
      QStandardItem *item = mp_factorsListModel->item(i, 0);
      if(item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_list << item->text();
        }
      QStandardItem *color_item = mp_factorsColorModel->item(i, 0);
      if(color_item->checkState() == Qt::CheckState(Qt::Checked))
        {
          factors_color << color_item->text();
        }
    }

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("tmp_path", getOutputTmpPath());
  grantlee_context.insert("factors_list", factors_list);
  grantlee_context.insert("factors_list_join",
                          transformQStringListInRListFormat(factors_list));
  grantlee_context.insert("factors_color",
                          transformQStringListInRListFormat(factors_color));
  grantlee_context.insert(
    "padjust",
    pappso::Utils::booleanToString(ui->padjust_switch->getSwitchValue()));
  grantlee_context.insert("alpha", ui->alpha_spin->value());


  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "protein_abundance", msp_rscriptTemplate->render(&grantlee_context));
  qDebug();
}

void
McqrSdsXicWidget::runProteinFcAbundance()
{
  qDebug();
  m_ongoingMcqrStep = SdsXicAnalysisStep::protein_fc_abundance;

  Grantlee::Context grantlee_context;
  grantlee_context.insert("mcqr_step", (std::int8_t)m_ongoingMcqrStep);
  grantlee_context.insert("tmp_path", getOutputTmpPath());
  grantlee_context.insert("fc_factor", ui->factor_combobox->currentText());
  grantlee_context.insert("num", ui->numerator_combobox->currentText());
  grantlee_context.insert("denom", ui->denominator_combobox->currentText());

  getMcqrRunParentView()->getRProcessRunning()->executeMcqrStep(
    "protein_fc_abundance", msp_rscriptTemplate->render(&grantlee_context));
  qDebug();
}

void
McqrSdsXicWidget::configureFilteringTab()
{
  qDebug();
  mp_factorLevelsToRemove = new QStandardItemModel(ui->levels_remove_view);
  // Configure combobox to store the list of factors
  for(QString factor : getMcqrExperimentSpLoaded().get()->getmetadataColumns())
    {
      qDebug() << factor;
      //       ui->factor_remove_comboBox->
      ui->factor_remove_combo->addItem(factor);
    }
  qDebug() << "fill combobox";
  ui->factor_remove_combo->setCurrentIndex(0);

  // Configure list view to represente levels from the first factor
  QString factor = ui->factor_remove_combo->currentText();
  updateLevelToRemoveList(factor);
  ui->levels_remove_view->setModel(mp_factorLevelsToRemove);

  ui->toolBox->setItemEnabled(1, true);
  ui->toolBox->setCurrentIndex(1);
  ui->toolBox->update();
  qDebug();
}

void
McqrSdsXicWidget::configureReconstitutingTab()
{
  qDebug();
  QStringList levels;
  for(McqrMetadata *metadata :
      getMcqrExperimentSpLoaded().get()->getmetadataInfoVector())
    {
      if(!levels.contains(metadata->m_otherData["track"].toString()))
        {
          levels << metadata->m_otherData["track"].toString();
        }
    }
  ui->track_ref_combobox->addItems(levels);


  ui->toolBox->setItemEnabled(2, true);
  ui->toolBox->setCurrentIndex(2);
  ui->toolBox->update();
  qDebug();
}

void
McqrSdsXicWidget::configureNormaliseTab()
{
  qDebug();
  QStringList levels;
  for(McqrMetadata *metadata :
      getMcqrExperimentSpLoaded().get()->getmetadataInfoVector())
    {
      if(m_mcqrLoadDataMode == McqrLoadDataMode::basic)
        {
          levels << metadata->m_msrunId;
        }
      else
        {
          if(!levels.contains(metadata->m_otherData["track"].toString()))
            {
              levels << metadata->m_otherData["track"].toString();
            }
        }
    }
  ui->norm_ref_track_combo->addItems(levels);

  ui->toolBox->setItemEnabled(3, true);
  ui->toolBox->setCurrentIndex(3);
  ui->toolBox->update();
  qDebug();
}

void
McqrSdsXicWidget::configureFcFactorList()
{
  qDebug();
  for(QString factor : getMcqrExperimentSpLoaded().get()->getmetadataColumns())
    {
      ui->factor_combobox->addItem(factor);
    }
  qDebug();
}

void
McqrSdsXicWidget::updateLevelToRemoveList(QString factor)
{
  qDebug() << factor;
  mp_factorLevelsToRemove->clear();

  QStringList levels;
  for(McqrMetadata *metadata :
      getMcqrExperimentSpLoaded().get()->getmetadataInfoVector())
    {
      QString new_level;
      if(factor == "msrun")
        {
          new_level = metadata->m_msrunId;
        }
      else if(factor == "msrunfile")
        {
          new_level = metadata->m_msrunFile;
        }
      else
        {
          new_level = metadata->m_otherData[factor].toString();
        }
      if(!levels.contains(new_level))
        {
          levels << new_level;
        }
    }
  int i = 0;
  for(QString level : levels)
    {
      QStandardItem *new_remove_level = new QStandardItem(level);
      new_remove_level->setCheckable(true);
      new_remove_level->setData(Qt::Unchecked, Qt::CheckStateRole);
      mp_factorLevelsToRemove->setItem(i, new_remove_level);

      i++;
    }
  //     ui->levels_remove_view->setModel(mp_factorLevelsToRemove);
  qDebug();
}

void
McqrSdsXicWidget::updateNumeratorAndDenominatorComboboxFc(QString factor)
{
  qDebug();
  ui->numerator_combobox->clear();
  ui->denominator_combobox->clear();
  QStringList factors_list;
  for(McqrMetadata *metadata :
      getMcqrExperimentSpLoaded().get()->getmetadataInfoVector())
    {
      if(!factors_list.contains(metadata->m_otherData[factor].toString()))
        {
          factors_list << metadata->m_otherData[factor].toString();
        }
    }
  for(QString factor_value : factors_list)
    {
      ui->denominator_combobox->addItem(factor_value);
      ui->numerator_combobox->addItem(factor_value);
    }
  qDebug();
}
