
/*******************************************************************************
 * Copyright (c) 2019 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:
 *     Thomas Renne <thomas.renne@u-psud.fr>. - initial API and
 *implementation
 ******************************************************************************/

#include <QDebug>
#include <QSettings>
#include <pappsomspp/pappsoexception.h>
#include "ui_ms_identification_run_view.h"
#include "msidentificationtableproxymodel.h"
#include "msidentificationtablemodel.h"
#include "msidentificationlistwindow.h"
#include "../../project_view/projectwindow.h"

MsIdentificationTableProxyModel::MsIdentificationTableProxyModel(
  MsIdentificationListWindow *msid_list_window,
  MsIdentificationTableModel *msid_table_model_p)
  : QSortFilterProxyModel(msid_table_model_p)
{
  m_msid_table_model_p = msid_table_model_p;
  m_msid_list_window   = msid_list_window;
  m_column_display.resize(30);
  qDebug() << "Test creation data";
  QSettings settings;
  for(std::size_t i = 0; i < m_column_display.size(); i++)
    {
      m_column_display[i] =
        settings
          .value(QString("ms_identification_list_columns/%1")
                   .arg(m_msid_table_model_p->getTitle(
                     (msIdentificationListColumn)i)),
                 "true")
          .toBool();
    }

  m_percent_delegate =
    new PercentItemDelegate(m_msid_list_window->ui->tableView);
}

MsIdentificationTableProxyModel::~MsIdentificationTableProxyModel()
{
}

bool
MsIdentificationTableProxyModel::filterAcceptsColumn(
  int source_column, const QModelIndex &source_parent [[maybe_unused]]) const
{
  return m_column_display[source_column];
}

bool
MsIdentificationTableProxyModel::filterAcceptsRow(
  int source_row, const QModelIndex &source_parent [[maybe_unused]]) const
{
  try
    {
      if(!m_ms_id_search_string.isEmpty())
        {
          if(m_search_on == "Identification File")
            {
              if(!m_msid_table_model_p->getIdentificationDataSourceSpList()
                    .at(source_row)
                    ->getResourceName()
                    .contains(m_ms_id_search_string))
                {
                  return false;
                }
            }
          else if(m_search_on == "ms identification")
            {
              if(!m_msid_table_model_p->getIdentificationDataSourceSpList()
                    .at(source_row)
                    ->getXmlId()
                    .contains(m_ms_id_search_string))
                {
                  return false;
                }
            }
          else if(m_search_on == "peak-list file")
            {
              if(!m_msid_table_model_p->getIdentificationDataSourceSpList()
                    .at(source_row)
                    ->getMsRunSp()
                    .get()
                    ->getFileName()
                    .contains(m_ms_id_search_string))
                {
                  return false;
                }
            }
        }
    }

  catch(pappso::PappsoException &exception_pappso)
    {
      // QMessageBox::warning(this,
      //                     tr("Error in ProteinTableModel::acceptRow :"),
      //                     exception_pappso.qwhat());
      qDebug() << "Error in ProteinTableModel::acceptRow :"
               << exception_pappso.qwhat();
    }
  catch(std::exception &exception_std)
    {
      // QMessageBox::warning(this,
      //                    tr("Error in ProteinTableModel::acceptRow :"),
      //                    exception_std.what());
      qDebug() << "Error in ProteinTableModel::acceptRow :"
               << exception_std.what();
    }

  return true;

  // return true;
}


bool
MsIdentificationTableProxyModel::lessThan(const QModelIndex &left,
                                          const QModelIndex &right) const
{
  QVariant leftData  = sourceModel()->data(left);
  QVariant rightData = sourceModel()->data(right);
  if(leftData.type() == QVariant::UInt)
    {
      return leftData.toUInt() < rightData.toUInt();
    }
  if(leftData.type() == QVariant::UInt)
    {
      return leftData.toUInt() < rightData.toUInt();
    }
  if(leftData.type() == QVariant::Double)
    {
      return leftData.toDouble() < rightData.toDouble();
    }
  return leftData.toString() < rightData.toString();
}

void
MsIdentificationTableProxyModel::setSearchOn(QString search_on)
{
  m_search_on = search_on;
}

void
MsIdentificationTableProxyModel::setMsIdentificationSearchString(
  QString ms_id_search_string)
{
  m_ms_id_search_string = ms_id_search_string;
}

QVariant
MsIdentificationTableProxyModel::data(const QModelIndex &index, int role) const
{

  return sourceModel()->data(mapToSource(index), role);
}

bool
MsIdentificationTableProxyModel::setData(const QModelIndex &index,
                                         const QVariant &new_data,
                                         int role)
{
  return sourceModel()->setData(mapToSource(index), new_data, role);
}


Qt::ItemFlags
MsIdentificationTableProxyModel::flags(const QModelIndex &idx) const
{
  return sourceModel()->flags(mapToSource(idx));
}


QVariant
MsIdentificationTableProxyModel::headerData(int section,
                                            Qt::Orientation orientation,
                                            int role) const
{
  int col = mapToSource(index(0, section)).column();

  return sourceModel()->headerData(col, orientation, role);
}

void
MsIdentificationTableProxyModel::onTableClicked(const QModelIndex &index)
{
  QModelIndex source_index(this->mapToSource(index));
  int row = source_index.row();

  m_identificationEngine =
    m_msid_table_model_p->getIdentificationDataSourceSpList().at(row);

  msIdentificationListColumn col =
    (msIdentificationListColumn)source_index.column();
  if(col == msIdentificationListColumn::engine_name)
    {
      m_msid_list_window->askEngineDetailView(&m_identificationEngine);
    }
  qDebug() << "end " << index.row();
}

void
MsIdentificationTableProxyModel::setMsIdentificationListColumnDisplay(
  msIdentificationListColumn column, bool toggled)
{
  qDebug() << "begin " << toggled;
  beginResetModel();
  QSettings settings;
  settings.setValue(QString("ms_identification_list_columns/%1")
                      .arg(m_msid_table_model_p->getTitle(column)),
                    toggled);

  m_column_display[(std::int8_t)column] = toggled;
  endResetModel();

  resteItemDelegates();
}
bool
MsIdentificationTableProxyModel::getMsIdentificationListColumnDisplay(
  msIdentificationListColumn column) const
{
  return m_column_display[(std::int8_t)column];
}

void
MsIdentificationTableProxyModel::resteItemDelegates() const
{

  for(int i = 0; i < columnCount(); ++i)
    {
      m_msid_list_window->ui->tableView->setItemDelegateForColumn(
        i, m_msid_list_window->ui->tableView->itemDelegate());
      if(mapToSource(index(0, i)).column() ==
         (std::int8_t)msIdentificationListColumn::percent_assign)
        {
          m_msid_list_window->ui->tableView->setItemDelegateForColumn(
            i, m_percent_delegate);
        }
    }
}
