/* 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.
*/

/////////////////////// Qt includes
#include <QDebug>
#include <QHeaderView>
#include <QMouseEvent>


/////////////////////// Local includes
#include "fragmentOligomerTreeViewSortProxyModel.hpp"
#include "fragmentOligomerTreeView.hpp"
#include "oligomer.hpp"
#include "fragmentationDlg.hpp"
#include "application.hpp"
#include "fragmentOligomerTreeViewMimeData.hpp"


namespace massXpert
{

  FragmentOligomerTreeView::FragmentOligomerTreeView(QWidget *parent)
    : QTreeView(parent)
  {

    setAlternatingRowColors(true);
    setAllColumnsShowFocus(true);
  
    setSortingEnabled(true);
    setDragEnabled(true);
    
    connect(this,
	     SIGNAL(activated(const QModelIndex &)),
	     this,
	     SLOT(itemActivated(const QModelIndex &)));  

    QHeaderView *headerView = header();
  
    headerView->setClickable(true);
    headerView->setMovable(true);

    ////// Create the actions for the contextual menu.

    // Copy Mono
    copyMonoAct = new QAction(tr("Copy Mono To Clipboard"), this);
    copyMonoAct->setStatusTip(tr("Copies the monoisotopic mass list "
				   "to the clipboard"));
    connect(copyMonoAct, SIGNAL(triggered()), this, SLOT(copyMono()));
  
    // Copy Avg
    copyAvgAct = new QAction(tr("Copy Avg To Clipboard"), this);
    copyMonoAct->setStatusTip(tr("Copies the average mass list "
				   "to the clipboard"));
    connect(copyAvgAct, SIGNAL(triggered()), this, SLOT(copyAvg()));

    // And now create the contextual menu and add the actions to it.
    contextMenu = new QMenu(tr("Copy Mass List"), this);
    contextMenu->addAction(copyMonoAct);
    contextMenu->addAction(copyAvgAct);
  }


  FragmentOligomerTreeView::~FragmentOligomerTreeView()
  {
  }


  FragmentationDlg *
  FragmentOligomerTreeView::getParentDlg()
  {
    return mp_parentDlg;
  }

  void 
  FragmentOligomerTreeView::setParentDlg(FragmentationDlg *dlg)
  {
    Q_ASSERT(dlg);
    mp_parentDlg = dlg;
  }


  int 
  FragmentOligomerTreeView::selectedOligomers(OligomerList *oligomerList,
					     int index) const
  {
    Q_ASSERT(oligomerList);
    Q_ASSERT(index >= 0);
    Q_ASSERT(index <= oligomerList->size());

    int count = 0;
    int localIndex = index;
    
    QSortFilterProxyModel *sortModel = 
      static_cast<QSortFilterProxyModel *>(model());
    
    // For each selected oligomer, duplicate it and append to the list
    // passed as argument.

    QItemSelectionModel *selModel = selectionModel();
    
    QModelIndexList list = selModel->selectedRows();
        
    for (int iter = 0; iter < list.size(); ++iter)
      {
	QModelIndex oligomerIndex = list.at(iter);
	
	Q_ASSERT(oligomerIndex.isValid());

	QModelIndex sourceIndex = sortModel->mapToSource(oligomerIndex);

	FragmentOligomerTreeViewItem *childItem = 
	  static_cast<FragmentOligomerTreeViewItem *> 
	 (sourceIndex.internalPointer());
	
	FragmentOligomer *oligomer = childItem->oligomer();
	
	FragmentOligomer *newOligomer = new FragmentOligomer(*oligomer);
	
	// Create a NoDeletePointerProp, which might be used later by
	// the user of the list of oligomers to highlight regions in
	// the sequence editor.

	NoDeletePointerProp *prop = 
	  new NoDeletePointerProp("SEQUENCE_EDITOR_WND", 
				   static_cast<void *>
				  (mp_parentDlg->editorWnd()));
	
	newOligomer->appendProp(prop);
	
	oligomerList->insert(localIndex, newOligomer);
	
	++localIndex;
	++count;
      }
    
    return count;
  }
  
  
  QString *
  FragmentOligomerTreeView::selectedOligomersAsPlainText(bool withSequence) const
  {
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    QString *text = new QString();

    // We allocate a string in which we describe all the selected
    // items.

    QSortFilterProxyModel *sortModel = 
      static_cast<QSortFilterProxyModel *>(model());
    Q_ASSERT(sortModel);
    
    QItemSelectionModel *selModel = selectionModel();
    
    //    QModelIndexList list = selModel->selectedRows();
    QModelIndexList list = selModel->selectedIndexes();

    for (int iter = 0; iter < list.size(); ++iter)
      {
	QModelIndex oligomerIndex = list.at(iter);
	
	Q_ASSERT(oligomerIndex.isValid());

	QModelIndex sourceIndex = sortModel->mapToSource(oligomerIndex);

	// If we do not make the filtering below, based upon the
	// column index, then we would have 7 times the number of
	// QModelIndex because there are 7 columns!
	if (sourceIndex.column() != 0)
	  continue;
	
	FragmentOligomerTreeViewItem *childItem = 
	  static_cast<FragmentOligomerTreeViewItem *> 
	 (sourceIndex.internalPointer());
	
	FragmentOligomer *oligomer = childItem->oligomer();
	
	*text += QString("\nPattern: %1"
			  "\t: %2" "\t: %3" 
			  "\t:%4" "\t: %5"
			  "\t: %6"
			  "\t: %7")
	  .arg(oligomer->fragmentationPattern())
	  .arg(oligomer->name())
	  .arg(static_cast<CoordinateList *>(oligomer)->positionsAsText())
	  .arg(oligomer->mono(locale, MXP_OLIGOMER_DEC_PLACES))
	  .arg(oligomer->avg(locale, MXP_OLIGOMER_DEC_PLACES))
	  .arg(oligomer->charge())
	  .arg(oligomer->isModified());
	
	if(withSequence)
	  {
	    QString *sequence = oligomer->monomerText();
	    
	    *text += QString("\n%1\n")
	      .arg(*sequence);
	    
	    delete sequence;
	  }
      }

    *text += QString("\n");
    
    return text;
  }
  


  void 
  FragmentOligomerTreeView::mousePressEvent(QMouseEvent *mouseEvent)
  {
    if (mouseEvent->buttons() & Qt::LeftButton)
      {
	m_dragStartPos = mouseEvent->pos();
      }
    else if (mouseEvent->buttons() & Qt::RightButton)
      {
	contextMenu->popup(mouseEvent->globalPos());
	return;
      }
    
    QTreeView::mousePressEvent(mouseEvent);
  }


  void 
  FragmentOligomerTreeView::mouseMoveEvent(QMouseEvent *mouseEvent)
  {
    if (mouseEvent->buttons() & Qt::LeftButton)
      {
	int distance = 
	 (mouseEvent->pos() - m_dragStartPos).manhattanLength();
	
	if(distance >= QApplication::startDragDistance())
	  {
	    startDrag();
	    return;
	  }
      }
    
    QTreeView::mousePressEvent(mouseEvent);
  }


  void 
  FragmentOligomerTreeView::startDrag()
  {
    FragmentOligomerTreeViewMimeData *mimeData = 
      new FragmentOligomerTreeViewMimeData(this, 
					  mp_parentDlg->editorWnd(),
					  mp_parentDlg);
    
    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    //    drag->setPixmap(QPixmap(":/images/greenled.png"));
    drag->start(Qt::CopyAction);
  }
  
  
 void 
  FragmentOligomerTreeView::currentChanged(const QModelIndex &current, 
					    const QModelIndex &previous)
  {
    if (!current.isValid())
      return;

    FragmentOligomerTreeViewSortProxyModel *sortModel = 
      static_cast<FragmentOligomerTreeViewSortProxyModel *>(model());
  
    QModelIndex sourceIndex = sortModel->mapToSource(current);


    FragmentOligomerTreeViewItem *childItem = 
      static_cast<FragmentOligomerTreeViewItem *> 
     (sourceIndex.internalPointer());
  
    Oligomer *oligomer = childItem->oligomer();
    if (!oligomer)
      return;
  
    if (oligomer->startIndex() >= oligomer->polymer()->size())
      return;
  
    if (oligomer->endIndex() >= oligomer->polymer()->size())
      return;

    QString *text = 
      oligomer->polymer()->monomerText(oligomer->startIndex(),
					 oligomer->endIndex(),
					 true);
    
    // We are getting text for an oligomer; it cannot be empty,
    // because that would mean the oligomer has no monomers. In that
    // case it is not conceivable that the oligomer be in the
    // fragmentation product list.
    
    Q_ASSERT(!text->isEmpty());
      
    FragmentationDlg *mp_parentDlg = getParentDlg();
    mp_parentDlg->updateOligomerSequence(text);
  
    delete text;

    QTreeView::currentChanged(sourceIndex, previous);
  }


  void 
  FragmentOligomerTreeView::itemActivated(const QModelIndex &index)
  {
    if (!index.isValid())
      return;

    QSortFilterProxyModel *sortModel = 
      static_cast<QSortFilterProxyModel *>(model());
  
    QModelIndex sourceIndex = sortModel->mapToSource(index);

    FragmentOligomerTreeViewItem *childItem = 
      static_cast<FragmentOligomerTreeViewItem *> 
     (sourceIndex.internalPointer());
    
    Oligomer *oligomer = childItem->oligomer();

    if (!oligomer)
      {
	// We are in a partial cleavage item. If it is collapsed, expand
	// it, and vice-versa.

	if(isExpanded(sourceIndex))
	  collapse(sourceIndex);
	else
	  expand(sourceIndex);
      
	return;
      }
  
    if (oligomer->startIndex() >= oligomer->polymer()->size())
      return;
  
    if (oligomer->endIndex() >= oligomer->polymer()->size())
      return;

    SequenceEditorWnd *editorWnd = mp_parentDlg->editorWnd();
    editorWnd->mpa_editorGraphicsView->setSelection(oligomer->startIndex(),
						     oligomer->endIndex(),
						     false, false);
  }


  ///////// Contextual menu for copying to clipboard of mono/avg
  ///////// masses.
  void 
  FragmentOligomerTreeView::copyMono()
  {
    return copyMassList(MXT_MASS_MONO);
  }


  void 
  FragmentOligomerTreeView::copyAvg()
  {
    return copyMassList(MXT_MASS_AVG);
  }


  void  
  FragmentOligomerTreeView::copyMassList(int monoOrAvg)
  {
    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    QString massList;
  
    FragmentOligomerTreeViewModel *treeModel = 
      static_cast<FragmentOligomerTreeViewModel *>(model());
    Q_ASSERT(treeModel);
  
    int columnIndex = 0;
    
    if(monoOrAvg == MXT_MASS_MONO)
      columnIndex = FRAG_OLIGO_MONO_COLUMN;
    else if (monoOrAvg == MXT_MASS_AVG)
      columnIndex = FRAG_OLIGO_AVG_COLUMN;
    else
      qFatal("Fatal error at %s@%d. Program aborted.",
	     __FILE__, __LINE__);
    
    int rowCount = treeModel->rowCount();
    if (!rowCount)
      return;
  
    for (int iter = 0; iter < rowCount; ++iter)
      {
	QModelIndex oligomerIndex =
	  treeModel->index(iter, columnIndex, QModelIndex());

	if (!oligomerIndex.isValid())
	  qFatal("Fatal error at %s@%d. Program aborted.",
		 __FILE__, __LINE__);
	
	// We have to make sure we translate correctly from
	// locale-based textual representation of double numbers
	// to real double numbers.
	
	bool ok = false;
	
	QString valueString = 
	  treeModel->data(oligomerIndex, Qt::DisplayRole).toString();
	
	double value = 
	  locale.toDouble(valueString, &ok);
	
	if (!value && !ok)
	  qFatal("Fatal error at %s@%d. Program aborted.",
		 __FILE__, __LINE__);
	
	// double value = treeModel->data(oligomerIndex, 
	// 			    Qt::DisplayRole).toDouble();
	
	massList += locale.toString(value, 'f', MXP_OLIGOMER_DEC_PLACES);
	massList += "\n";
      }
  
    if (massList.isEmpty())
      return;
  
    QClipboard *clipboard = QApplication::clipboard();
  
    clipboard->setText(massList, QClipboard::Clipboard);
  }

} // namespace massXpert
