/* massXpert - the true massist's program.
   --------------------------------------
   Copyright(C) 2006,2007 Filippo Rusconi

   http://www.massxpert.org/massXpert

   This file is part of the massXpert project.

   The massxpert project is the successor to the "GNU polyxmass"
   project that is an official GNU project package(see
   www.gnu.org). The massXpert project is not endorsed by the GNU
   project, although it is released ---in its entirety--- under the
   GNU General Public License. A huge part of the code in massXpert
   is actually a C++ rewrite of code in GNU polyxmass. As such
   massXpert was started at the Centre National de la Recherche
   Scientifique(FRANCE), that granted me the formal authorization to
   publish it under this Free Software License.

   This software is free software; you can redistribute it and/or
   modify it under the terms of the GNU  General Public
   License version 3, as published by the Free Software Foundation.
   

   This software 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 software; if not, write to the

   Free Software Foundation, Inc.,

   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/


/////////////////////// Local includes
#include "mzCalculationTreeViewModel.hpp"
#include "mzCalculationTreeViewItem.hpp"
#include "application.hpp"


namespace massXpert
{

  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)
  {
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    Q_ASSERT(ionizable);
  
    QList<QVariant> columnData;
  
    int level = 
      ionizable->ionizeRule()->charge() * ionizable->ionizeRule()->level() ;
    
    QString mono = ionizable->mono(locale, MXP_OLIGOMER_DEC_PLACES);
    QString avg = ionizable->avg(locale, MXP_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)
  {
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    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->mono(locale, MXP_OLIGOMER_DEC_PLACES);
	QString avg = ionizable->avg(locale, MXP_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 massXpert
