/**
 * \file gui/widgets/contaminant_widget/contaminantwidget.cpp
 * \date 20/2/2018
 * \author Olivier Langella
 * \brief graphic widget to choose contaminant files or regular expression
 */

/*******************************************************************************
 * Copyright (c) 2018 Olivier Langella <olivier.langella@u-psud.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/>.
 *
 * Contributors:
 *     Olivier Langella <olivier.langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/


#include "contaminantwidget.h"

#include "ui_contaminant_widget.h"
#include <QDebug>
#include <pappsomspp/core/pappsoexception.h>
#include <QSettings>
#include <QFileDialog>

ContaminantWidget::ContaminantWidget(QWidget *parent)
  : QWidget(parent), ui(new Ui::ContaminantWidget)
{
  qDebug();
  ui->setupUi(this);
  _emit_changed   = false;
  _p_fasta_str_li = new QStandardItemModel();
  ui->contaminant_database_listview->setModel(_p_fasta_str_li);
  // QItemSelectionModel *selection_model =
  //  ui->contaminant_database_listview->selectionModel();
  ui->contaminant_database_listview->setSelectionMode(
    QAbstractItemView::MultiSelection);

  doSelectContaminantSource();
  _emit_changed = true;
  qDebug();
}

ContaminantWidget::~ContaminantWidget()
{
  qDebug();
  delete ui;
  delete _p_fasta_str_li;
  qDebug();
}


void
ContaminantWidget::setRegexpContaminantPattern(const QString &pattern)
{
  _emit_changed = false;
  ui->contaminant_protein_regexp_line_edit->setText(pattern);
  _emit_changed = true;
}


void
ContaminantWidget::setFastaFileList(
  const std::vector<FastaFileSp> &fasta_file_list,
  const std::vector<const FastaFile *> &contaminant_fasta_file_list)
{

  _p_fasta_str_li->removeRows(0, _p_fasta_str_li->rowCount());
  std::size_t i = 0;
  for(FastaFileSp fasta_file : fasta_file_list)
    {

      QStandardItem *item;
      item =
        new QStandardItem(QString("%1").arg(fasta_file.get()->getFilename()));
      item->setEditable(false);
      item->setData(QVariant::fromValue(fasta_file), Qt::UserRole);
      _p_fasta_str_li->appendRow(item);
      i++;
      // item->setData(QVariant(QString("%1").arg(fasta_file.get()->getAbsoluteFilePath())),Qt::UserRole);
      if(std::find(contaminant_fasta_file_list.begin(),
                   contaminant_fasta_file_list.end(),
                   fasta_file.get()) != contaminant_fasta_file_list.end())
        {
          // item->setCheckState(Qt::Checked);
          // sm->isRowSelected(i);
          ui->contaminant_database_listview->setCurrentIndex(
            ui->contaminant_database_listview->model()->index(i, 0));
        }
    }
}

void
ContaminantWidget::getProjectContaminants(const Project *p_project)
{
  _emit_changed = false;

  this->setFastaFileList(
    p_project->getFastaFileStore().getFastaFileList(),
    p_project->getProteinStore().getContaminantFastaFileList());
  ui->contaminant_regexp_radiobutton->setChecked(true);
  ui->contaminant_protein_regexp_line_edit->setVisible(true);
  ui->contaminant_file_widget->setVisible(false);
  if(p_project->getProteinStore().getContaminantSelectionType() ==
     ContaminantSelectionType::fastaFiles)
    {
      qDebug()
        << p_project->getProteinStore().getContaminantFastaFileList().size();
      ui->contaminant_file_radiobutton->setChecked(true);
      ui->contaminant_protein_regexp_line_edit->setVisible(false);
      ui->contaminant_file_widget->setVisible(true);
    }
  if(p_project->getProteinStore().getContaminantSelectionType() ==
     ContaminantSelectionType::regexp)
    {
      ui->contaminant_regexp_radiobutton->setChecked(true);

      ui->contaminant_protein_regexp_line_edit->setText(
        p_project->getProteinStore().getRegexpContaminant().pattern());
    }

  ContaminantRemovalMode mode = p_project->getContaminantRemovalMode();
  switch(mode)
    {
      case ContaminantRemovalMode::before:
        ui->contaminant_mode_before_radio_button->setChecked(true);
        break;

      default:
        ui->contaminant_mode_groups_radio_button->setChecked(true);
        break;
    }


  ui->control_list_widget->setVisible(false);
  _no_project   = false;
  _emit_changed = true;
}

void
ContaminantWidget::setProjectContaminants(Project *p_project)
{
  qDebug();
  _emit_changed = false;
  try
    {
      if(ui->contaminant_mode_before_radio_button->isChecked())
        {
          p_project->setContaminantRemovalMode(ContaminantRemovalMode::before);
        }
      else
        {
          p_project->setContaminantRemovalMode(ContaminantRemovalMode::groups);
        }
      if(ui->contaminant_file_radiobutton->isChecked())
        {
          QModelIndexList index_list =
            ui->contaminant_database_listview->selectionModel()
              ->selectedIndexes();
          p_project->getProteinStore().clearContaminants();
          p_project->getProteinStore().setContaminantSelectionType(
            ContaminantSelectionType::fastaFiles);
          if(index_list.size() > 0)
            {
              for(QModelIndex index : index_list)
                {
                  if(index.data(Qt::UserRole).canConvert<FastaFileSp>())
                    {
                      FastaFileSp p_fasta_file =
                        index.data(Qt::UserRole).value<FastaFileSp>();
                      p_fasta_file.get()->setContaminants(
                        p_project->getProteinStore());
                    }
                  else
                    {
                      throw pappso::PappsoException(
                        QObject::tr("can not convert to FastaFile "
                                    "index.data().canConvert<FastaFile *>()"));
                    }
                }
            }

          if(_no_project)
            {
              ui->control_list_widget->setVisible(true);
            }
        }
      else
        {
          p_project->getProteinStore().setRegexpContaminantPattern(
            ui->contaminant_protein_regexp_line_edit->text());
          ui->control_list_widget->setVisible(false);
          p_project->getProteinStore().setContaminantSelectionType(
            ContaminantSelectionType::regexp);
        }
    }

  catch(pappso::PappsoException &exception_pappso)
    {
      _emit_changed = true;
      throw exception_pappso;
    }
  catch(std::exception &exception_std)
    {
      _emit_changed = true;
      throw exception_std;
    }
  _emit_changed = true;
  qDebug();
}


void
ContaminantWidget::doChanged()
{
  qDebug();
  if(_emit_changed)
    emit changed();
  qDebug();
}

void
ContaminantWidget::doSelectContaminantSource()
{
  qDebug();
  ui->contaminant_file_widget->setVisible(false);
  ui->contaminant_protein_regexp_line_edit->setVisible(false);
  if(ui->contaminant_file_radiobutton->isChecked())
    {
      ui->contaminant_file_widget->setVisible(true);
    }
  else
    {
      ui->contaminant_protein_regexp_line_edit->setVisible(true);
    }
  if(_emit_changed)
    emit changed();
  qDebug();
}


void
ContaminantWidget::doSelectContaminantMode()
{
  qDebug();
  ui->contaminant_file_widget->setVisible(false);
  ui->contaminant_protein_regexp_line_edit->setVisible(false);
  if(ui->contaminant_file_radiobutton->isChecked())
    {
      ui->contaminant_file_widget->setVisible(true);
    }
  else
    {
      ui->contaminant_protein_regexp_line_edit->setVisible(true);
    }
  if(_emit_changed)
    emit changed();
  qDebug();
}

void
ContaminantWidget::doSelectFastaFile()
{
  try
    {
      QSettings settings;
      QString default_fasta_location =
        settings.value("path/fastafiles_directory", "").toString();

      QStringList filenames = QFileDialog::getOpenFileNames(
        this,
        tr("FASTA files"),
        default_fasta_location,
        tr("FASTA files (*.fasta);;all files (*)"));

      if(filenames.size() > 0)
        {
          settings.setValue("path/fastafiles_directory",
                            QFileInfo(filenames[0]).absolutePath());
        }

      std::vector<FastaFileSp> fasta_file_list;
      for(QString filename : filenames)
        {
          fasta_file_list.push_back(std::make_shared<FastaFile>(filename));
        }


      for(FastaFileSp fasta_file : fasta_file_list)
        {

          QStandardItem *item;
          item = new QStandardItem(
            QString("%1").arg(fasta_file.get()->getFilename()));
          item->setEditable(false);
          item->setData(QVariant::fromValue(fasta_file), Qt::UserRole);
          _p_fasta_str_li->appendRow(item);
          // item->setData(QVariant(QString("%1").arg(fasta_file.get()->getAbsoluteFilePath())),Qt::UserRole);
        }
    }
  catch(pappso::PappsoException &error)
    {
      // QMessageBox::warning(this,
      //                  tr("Error choosing identification result files :
      //                  %1").arg(error.qwhat()), error);
    }
}
void
ContaminantWidget::doClearList()
{
  _p_fasta_str_li->removeRows(0, _p_fasta_str_li->rowCount());
}
