/**
 * \file gui/widgets/decoy_widget/decoywidget.cpp
 * \date 20/2/2018
 * \author Olivier Langella
 * \brief graphic widget to choose decoy 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/>.
 *
 ******************************************************************************/


#include "decoywidget.h"

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

DecoyWidget::DecoyWidget(QWidget *parent)
  : QWidget(parent), ui(new Ui::DecoyWidget)
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  ui->setupUi(this);
  _emit_changed   = false;
  _p_fasta_str_li = new QStandardItemModel();
  ui->decoy_database_listview->setModel(_p_fasta_str_li);
  // QItemSelectionModel *selection_model =
  // ui->decoy_database_listview->selectionModel();
  ui->decoy_database_listview->setSelectionMode(
    QAbstractItemView::MultiSelection);

  doSelectDecoySource();
  _emit_changed = true;
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}

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


void
DecoyWidget::setRegexpDecoyPattern(const QString &pattern)
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  _emit_changed = false;
  ui->decoy_protein_regexp_line_edit->setText(pattern);
  _emit_changed = true;
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}


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

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

  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}

void
DecoyWidget::getProjectDecoys(const Project *p_project)
{

  qDebug();
  _emit_changed = false;
  ui->decoy_regexp_radiobutton->setChecked(true);
  ui->decoy_protein_regexp_line_edit->setVisible(true);
  ui->decoy_database_listview->setVisible(false);

  if(p_project->getProteinStore().getDecoySelectionType() ==
     DecoySelectionType::fastaFiles)
    {
      if(p_project->getProteinStore().getDecoyFastaFileList().size() > 0)
        {
          ui->decoy_file_radiobutton->setChecked(true);
          ui->decoy_protein_regexp_line_edit->setVisible(false);
          ui->decoy_database_listview->setVisible(true);
        }
    }
  if(p_project->getProteinStore().getDecoySelectionType() ==
     DecoySelectionType::regexp)
    {
      ui->decoy_regexp_radiobutton->setChecked(true);
      ui->decoy_protein_regexp_line_edit->setText(
        p_project->getProteinStore().getRegexpDecoy().pattern());
    }

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

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

  qDebug();
}

void
DecoyWidget::setProjectDecoys(Project *p_project)
{
  qDebug();

  _emit_changed = false;
  try
    {
      if(ui->decoy_file_radiobutton->isChecked())
        {
          p_project->getProteinStore().setDecoySelectionType(
            DecoySelectionType::fastaFiles);
          QModelIndexList index_list =
            ui->decoy_database_listview->selectionModel()->selectedIndexes();
          p_project->getProteinStore().clearDecoys();
          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()->setDecoys(
                        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().setDecoySelectionType(
            DecoySelectionType::regexp);
          p_project->getProteinStore().setRegexpDecoyPattern(
            ui->decoy_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
DecoyWidget::doChanged()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__
           << _emit_changed;
  if(_emit_changed)
    emit changed();
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}

void
DecoyWidget::doSelectDecoySource()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  ui->decoy_database_listview->setVisible(false);
  ui->decoy_protein_regexp_line_edit->setVisible(false);
  if(ui->decoy_file_radiobutton->isChecked())
    {
      ui->decoy_database_listview->setVisible(true);
    }
  else
    {
      ui->decoy_protein_regexp_line_edit->setVisible(true);
    }
  if(_emit_changed)
    emit changed();
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}


void
DecoyWidget::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
DecoyWidget::doClearList()
{
  _p_fasta_str_li->removeRows(0, _p_fasta_str_li->rowCount());
}
