/**
 * \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 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:
 *     Olivier Langella <olivier.langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/


#include "contaminantwidget.h"

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

ContaminantWidget::ContaminantWidget(QWidget *parent)
  : QWidget(parent), ui(new Ui::ContaminantWidget)
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  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() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}

ContaminantWidget::~ContaminantWidget()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  delete ui;
  delete _p_fasta_str_li;
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}


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


void
ContaminantWidget::setFastaFileList(std::vector<FastaFileSp> fasta_file_list)
{

  _p_fasta_str_li->removeRows(0, _p_fasta_str_li->rowCount());
  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);
    }
}

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

  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->contaminant_regexp_radiobutton->setChecked(true);
  ui->contaminant_protein_regexp_line_edit->setVisible(true);
  ui->contaminant_file_widget->setVisible(false);
  if(p_project->getProteinStore().getContaminantFastaFileList().size() > 0)
    {
      ui->contaminant_file_radiobutton->setChecked(true);
      ui->contaminant_protein_regexp_line_edit->setVisible(false);
      ui->contaminant_file_widget->setVisible(true);
    }

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

  this->setFastaFileList(p_project->getFastaFileStore().getFastaFileList());

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

void
ContaminantWidget::setProjectContaminants(Project *p_project)
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  _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();
          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);
        }
    }

  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() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}


void
ContaminantWidget::doChanged()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  if(_emit_changed)
    emit changed();
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}

void
ContaminantWidget::doSelectContaminantSource()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  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() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}


void
ContaminantWidget::doSelectContaminantMode()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  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() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}

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());
}
