/**
 * \file gui/ptm_island_list_window/ptmislandproxymodel.cpp
 * \date 30/5/2017
 * \author Olivier Langella
 * \brief display all ptm islands
 */

/*******************************************************************************
 * Copyright (c) 2017 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 <QSettings>
#include "ptmislandproxymodel.h"
#include "ptmislandtablemodel.h"
#include "ptmislandlistwindow.h"
#include "../../grouping/ptm/ptmgroupingexperiment.h"
#include "../../grouping/ptm/ptmisland.h"
#include <pappsomspp/core/pappsoexception.h>

PtmIslandProxyModel::PtmIslandProxyModel(
  PtmIslandListWindow *p_ptm_island_list_window,
  PtmIslandTableModel *ptm_table_model_p)
{
  _p_ptm_island_list_window = p_ptm_island_list_window;
  _p_ptm_island_table_model = ptm_table_model_p;
  _ptm_search_string        = "";
  _search_on                = "accession";
  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("ptm_island_columns/%1")
              .arg(_p_ptm_island_table_model->getTitle((PtmIslandListColumn)i)),
            "true")
          .toBool();
    }
}

PtmIslandProxyModel::~PtmIslandProxyModel()
{
}

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

bool
PtmIslandProxyModel::filterAcceptsRow(int source_row,
                                      const QModelIndex &source_parent
                                      [[maybe_unused]]) const
{
  try
    {
      // qDebug() << "ProteinTableProxyModel::filterAcceptsRow begin " <<
      // source_row;
      PtmIslandSp sp_ptm_island =
        _p_ptm_island_table_model->getPtmGroupingExperiment()
          ->getPtmIslandList()
          .at(source_row);
      // qDebug() << "Prote
      // qDebug() << "ProteinTableProxyModel::filterAcceptsRow protein_match "
      // << source_row;
      if(m_hideNotChecked)
        {
          if(!sp_ptm_island->isChecked())
            {
              return false;
            }
        }
      if(!_ptm_search_string.isEmpty())
        {
          if(_search_on == "accession")
            {
              if(!sp_ptm_island.get()
                    ->getProteinMatch()
                    ->getProteinXtpSp()
                    .get()
                    ->getAccession()
                    .contains(_ptm_search_string))
                {
                  return false;
                }
            }
          else if(_search_on == "group")
            {
              if(!sp_ptm_island.get()->getGroupingId().startsWith(
                   QString("ptm%1").arg(_ptm_search_string)))
                {
                  return false;
                }
            }
          else if(_search_on == "sequence")
            {
              if(!sp_ptm_island.get()
                    ->getProteinMatch()
                    ->getProteinXtpSp()
                    .get()
                    ->getSequence()
                    .contains(_ptm_search_string))
                {
                  return false;
                }
            }
          else if(_search_on == "peptide")
            {
              QString peptide_search_string =
                QString(_ptm_search_string).replace("L", "I");
              for(const PeptideMatch &p_peptide_match :
                  sp_ptm_island.get()->getProteinMatch()->getPeptideMatchList())
                {
                  if(p_peptide_match.getPeptideEvidence()
                       ->getPeptideXtpSp()
                       .get()
                       ->getSequenceLi()
                       .contains(peptide_search_string))
                    {
                      return true;
                    }
                }
              return false;
            }

          else if(_search_on == "description")
            {
              // description
              if(!sp_ptm_island.get()
                    ->getProteinMatch()
                    ->getProteinXtpSp()
                    .get()
                    ->getDescription()
                    .contains(_ptm_search_string))
                {
                  return false;
                }
            }
        }
      if(sp_ptm_island != nullptr)
        {
          return true;
        }
      return false;
    }

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

  return true;

  // return true;
}


void
PtmIslandProxyModel::onTableClicked(const QModelIndex &index)
{
  qDebug() << "PtmIslandProxyModel::onTableClicked begin " << index.row();
  qDebug() << "PtmIslandProxyModel::onTableClicked begin "
           << this->mapToSource(index).row();

  //   _protein_table_model_p->onTableClicked(this->mapToSource(index));
  QModelIndex source_index(this->mapToSource(index));
  int row = source_index.row();
  int col = source_index.column();

  PtmIslandSp ptm_island_sp =
    _p_ptm_island_table_model->getPtmGroupingExperiment()
      ->getPtmIslandList()
      .at(row);

  if(col == (std::int8_t)PtmIslandListColumn::checked)
    {
      if(ptm_island_sp->isChecked())
        {
          ptm_island_sp->setChecked(false);
        }
      else
        {
          ptm_island_sp->setChecked(true);
        }
      _p_ptm_island_list_window->edited();
    }
  else if((col == (std::int8_t)PtmIslandListColumn::accession) ||
          (col == (std::int8_t)PtmIslandListColumn::description))
    {
      ProteinMatch *p_protein_match = ptm_island_sp->getProteinMatch();
      _p_ptm_island_list_window->askProteinDetailView(p_protein_match);
    }
  else
    {
      _p_ptm_island_list_window->askViewPtmPeptideList(
        _p_ptm_island_table_model->getPtmGroupingExperiment()
          ->getPtmIslandList()
          .at(row)
          .get());
    }

  qDebug() << "PtmIslandProxyModel::onTableClicked end " << index.row();
}

bool
PtmIslandProxyModel::getPtmIslandListColumnDisplay(
  PtmIslandListColumn column) const
{
  return m_column_display[(std::int8_t)column];
}

void
PtmIslandProxyModel::setPtmIslandListColumnDisplay(PtmIslandListColumn column,
                                                   bool toggled)
{
  qDebug() << "begin " << toggled;
  beginResetModel();
  QSettings settings;
  settings.setValue(QString("ptm_island_columns/%1")
                      .arg(_p_ptm_island_table_model->getTitle(column)),
                    toggled);

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

void
PtmIslandProxyModel::hideNotChecked(bool hide)
{
  m_hideNotChecked = hide;
}


void
PtmIslandProxyModel::setSearchOn(QString search_on)
{
  _search_on = search_on;
}

void
PtmIslandProxyModel::setPtmSearchString(QString ptm_search_string)
{
  _ptm_search_string = ptm_search_string;
}
