/**
 * \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() << "ContaminantWidget::ContaminantWidget begin";
    ui->setupUi(this);

    _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();
    qDebug() << "ContaminantWidget::ContaminantWidget end";
}

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


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


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) {
    ui->contaminant_regexp_radiobutton->setChecked(true);
    ui->contaminant_protein_regexp_line_edit->setVisible(true);
    ui->contaminant_database_listview->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_database_listview->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;
}

void ContaminantWidget::setProjectContaminants(Project * p_project) {
    qDebug() << "ContaminantWidget::setProjectContaminants begin";
    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);
    }
    qDebug() << "ContaminantWidget::setProjectContaminants end";
}


void ContaminantWidget::doSelectContaminantSource() {
    qDebug() << "ContaminantWidget::doSelectContaminantSource begin";
    ui->contaminant_database_listview->setVisible(false);
    ui->contaminant_protein_regexp_line_edit->setVisible(false);
    if (ui->contaminant_file_radiobutton->isChecked()) {
        ui->contaminant_database_listview->setVisible(true);
    }
    else {
        ui->contaminant_protein_regexp_line_edit->setVisible(true);
    }
    qDebug() << "ContaminantWidget::doSelectContaminantSource end";
}


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