/* BEGIN software license
 *
 * msXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright(C) 2009,...,2018 Filippo Rusconi
 *
 * http://www.msxpertsuite.org
 *
 * This file is part of the msXpertSuite project.
 *
 * The msXpertSuite project is the successor of the massXpert project. This
 * project now includes various independent modules:
 *
 * - massXpert, model polymer chemistries and simulate mass spectrometric data;
 * - mineXpert, a powerful TIC chromatogram/mass spectrum viewer/miner;
 *
 * This program 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.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * END software license
 */


/////////////////////// Local includes
#include <massxpert/gui/MzCalculationTreeViewModel.hpp>
#include <massxpert/gui/MzCalculationTreeViewItem.hpp>


namespace msXpSmassXpert
{

MzCalculationTreeViewModel::MzCalculationTreeViewModel(
  QList<Ionizable *> *dataList, QObject *parent)
  : QAbstractItemModel(parent)
{
  QList<QVariant> rootData;

  Q_ASSERT(dataList);
  Q_ASSERT(parent);

  mp_parentDlg = static_cast<MzCalculationDlg *>(parent);

  rootData << tr("Charge") << tr("Mono") << tr("Avg");

  mpa_rootItem = new MzCalculationTreeViewItem(rootData);

  mp_list = dataList;
  setupModelData(mpa_rootItem);
}


MzCalculationTreeViewModel::~MzCalculationTreeViewModel()
{
  delete mpa_rootItem;
}


MzCalculationDlg *
MzCalculationTreeViewModel::getParentDlg()
{
  return mp_parentDlg;
}


void
MzCalculationTreeViewModel::setTreeView(QTreeView *treeView)
{
  Q_ASSERT(treeView);

  mp_treeView = treeView;
}


QTreeView *
MzCalculationTreeViewModel::treeView()
{
  return mp_treeView;
}


QVariant
MzCalculationTreeViewModel::data(const QModelIndex &index, int role) const
{
  if(!index.isValid())
    return QVariant();

  if(role != Qt::DisplayRole)
    return QVariant();

  MzCalculationTreeViewItem *item =
    static_cast<MzCalculationTreeViewItem *>(index.internalPointer());

  return item->data(index.column());
}


QVariant
MzCalculationTreeViewModel::headerData(int section,
                                       Qt::Orientation orientation,
                                       int role) const
{
  if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
    return mpa_rootItem->data(section);

  return QVariant();
}


Qt::ItemFlags
MzCalculationTreeViewModel::flags(const QModelIndex &index) const
{
  if(!index.isValid())
    return Qt::ItemIsEnabled;

  return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}


QModelIndex
MzCalculationTreeViewModel::index(int row,
                                  int column,
                                  const QModelIndex &parent) const
{
  MzCalculationTreeViewItem *parentItem = 0;

  if(!parent.isValid())
    parentItem = mpa_rootItem;
  else
    parentItem =
      static_cast<MzCalculationTreeViewItem *>(parent.internalPointer());

  MzCalculationTreeViewItem *childItem = parentItem->child(row);
  if(childItem != 0)
    return createIndex(row, column, childItem);
  else
    return QModelIndex();
}


QModelIndex
MzCalculationTreeViewModel::parent(const QModelIndex &index) const
{
  if(!index.isValid())
    return QModelIndex();

  MzCalculationTreeViewItem *childItem =
    static_cast<MzCalculationTreeViewItem *>(index.internalPointer());

  MzCalculationTreeViewItem *parentItem = childItem->parent();

  if(parentItem == mpa_rootItem)
    return QModelIndex();

  return createIndex(parentItem->row(), 0, parentItem);
}


int
MzCalculationTreeViewModel::rowCount(const QModelIndex &parent) const
{
  MzCalculationTreeViewItem *parentItem;

  if(!parent.isValid())
    parentItem = mpa_rootItem;
  else
    parentItem =
      static_cast<MzCalculationTreeViewItem *>(parent.internalPointer());

  return parentItem->childCount();
}


int
MzCalculationTreeViewModel::columnCount(const QModelIndex &parent) const
{
  if(parent.isValid())
    return static_cast<MzCalculationTreeViewItem *>(parent.internalPointer())
      ->columnCount();
  else
    return mpa_rootItem->columnCount();
}


void
MzCalculationTreeViewModel::removeAll()
{
  int count = rowCount();

  if(!count)
    return;

  // On WinXP , the following beginRemoveRows crashes when count is 0,
  // because last>=first fails, due to having count-1 < than 0. This
  // is why we return immediately when count is 0.
  beginRemoveRows(QModelIndex(), 0, count - 1);

  while(!mp_list->isEmpty())
    {
      delete(mp_list->takeFirst());

      delete(mpa_rootItem->takeChild(0));
    }

  endRemoveRows();

  emit layoutChanged();
}


void
MzCalculationTreeViewModel::addIonizable(Ionizable *ionizable)
{
  Q_ASSERT(ionizable);

  QList<QVariant> columnData;

  int level =
    ionizable->ionizeRule()->charge() * ionizable->ionizeRule()->level();

  QString mono = ionizable->monoString(msXpS::OLIGOMER_DEC_PLACES);
  QString avg  = ionizable->avgString(msXpS::OLIGOMER_DEC_PLACES);

  columnData << level << mono << avg;

  mp_list->append(ionizable);

  // Create an item with those columnar strings. The parent of the
  // current item is the root item.
  MzCalculationTreeViewItem *newItem =
    new MzCalculationTreeViewItem(columnData, mpa_rootItem);

  newItem->setIonizable(ionizable);

  int newRow = rowCount();

  mpa_rootItem->appendChild(newItem);

  //   qDebug() << __FILE__ << __LINE__
  // 	    << "Appended new item:" << newItem
  // 	    << "with ionizable:" << newItem->ionizable();

  // There is no need to produce a model index for the parent, as we
  // know we are going to insert new row in the root of the tree(this
  // tree has no branches). Hence the QModelIndex() calls below.

  beginInsertRows(QModelIndex(), newRow, newRow);
  insertRow(newRow, QModelIndex());
  endInsertRows();

  emit layoutChanged();

#if 0
    for (int iter = 0 ; iter < mp_list->size() ; ++iter)
      {
	qDebug() << __FILE__ << __LINE__
		  << "Test mp_list:"
		  << "Ionizable:" << mp_list->at(iter)
		  << mp_list->at(iter)->mono()
		  << mp_list->at(iter)->avg()
		  << "End of test";
      }

    for (int iter = 0 ; iter < mpa_rootItem->childCount() ; ++iter)
      {
	qDebug() << __FILE__ << __LINE__
		  << "Test mpa_rootItem:"
		  << "Ionizable:" << mpa_rootItem->child(iter)->ionizable()
		  << mpa_rootItem->child(iter)->ionizable()->mono()
		  << mpa_rootItem->child(iter)->ionizable()->avg()
		  << "End of test";
      }
#endif
}


bool
MzCalculationTreeViewModel::setupModelData(MzCalculationTreeViewItem *parent)
{
  QList<MzCalculationTreeViewItem *> parents;
  MzCalculationTreeViewItem *currentItem = 0;

  Q_ASSERT(parent);

  // Start with populating the very first item of the treeviewmodel.
  parents << parent;

  // We have the mp_list pointer that points to a QList<Ionizable*>
  // list.

  for(int iter = 0; iter < mp_list->size(); ++iter)
    {
      Ionizable *ionizable = mp_list->at(iter);

      QList<QVariant> columnData;

      int charge =
        ionizable->ionizeRule()->charge() * ionizable->ionizeRule()->level();

      QString mono = ionizable->monoString(msXpS::OLIGOMER_DEC_PLACES);
      QString avg  = ionizable->avgString(msXpS::OLIGOMER_DEC_PLACES);

      columnData << charge << mono << avg;


      // Create an item with those columnar strings. The parent of the
      // current item is parents.
      currentItem = new MzCalculationTreeViewItem(columnData, parents[0]);

      currentItem->setIonizable(ionizable);

      //       qDebug() << __FILE__ << __LINE__
      // 		<< "Set new ion:" << ion;

      // We should append that item right now.
      parents[0]->appendChild(currentItem);

      // At this point we have finished setting up the Model data.
    }

  return true;
}

} // namespace msXpSmassXpert
