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


/////////////////////// Local includes
#include "application.hpp"
#include "polymerModificationDlg.hpp"


namespace massXpert
{

  PolymerModificationDlg::PolymerModificationDlg(QWidget *parent, 
						  PolymerEnd end)
    : QDialog(parent)
  {

    m_ui.setupUi(this);
    Q_ASSERT(parent);
  
    mp_editorWnd = static_cast<SequenceEditorWnd *>(parent);

    populateModificationList();
    
    if (mp_editorWnd)
      updateModificationLineEdits();
    
    
    if (end & MXT_END_LEFT)
      m_ui.leftEndCheckBox->setChecked(true);
    
    if (end & MXT_END_RIGHT)
      m_ui.rightEndCheckBox->setChecked(true);
    
  
    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
  
    settings.beginGroup("polymer_modification_dlg");

    restoreGeometry(settings.value("geometry").toByteArray());
  
    settings.endGroup();

    connect(this,
	     SIGNAL(rejected()),
	     this,
	     SLOT(close()));

    connect(m_ui.modifyPushButton,
	     SIGNAL(clicked()),
	     this,
	     SLOT(modify()));

    connect(m_ui.unmodifyPushButton,
	     SIGNAL(clicked()),
	     this,
	     SLOT(unmodify()));
  }


  PolymerModificationDlg::~PolymerModificationDlg()
  {
  }


  void 
  PolymerModificationDlg::closeEvent(QCloseEvent *event)
  {
    if (event)
      printf("%s", "");
  
    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
  
    settings.beginGroup("polymer_modification_dlg");

    settings.setValue("geometry", saveGeometry());

    settings.endGroup();
  }



  void
  PolymerModificationDlg::updateModificationLineEdits()
  {
    Polymer *polymer = mp_editorWnd->polymer();

    m_ui.leftEndLineEdit->setText(QString("%1 = %2")
				   .arg(polymer->leftEndModif().formula())
				   .arg(polymer->leftEndModif().name()));

    m_ui.rightEndLineEdit->setText(QString("%1 = %2")
				    .arg(polymer->rightEndModif().formula())
				    .arg(polymer->rightEndModif().name()));
  }


  bool
  PolymerModificationDlg::populateModificationList()
  {
    PolChemDef *polChemDef = mp_editorWnd->polChemDef();
    Q_ASSERT(polChemDef);
  
    for (int iter = 0; iter < polChemDef->modifList().size(); ++iter)
      {
	Modif *modif = polChemDef->modifList().at(iter);
	Q_ASSERT(modif);
      
	m_ui.modifListWidget->addItem(modif->name());
      }
  
    return true;
  }


  bool 
  PolymerModificationDlg::parseModifDefinition(Modif *modif)
  {
    Q_ASSERT(modif);
  
    QString text = m_ui.modifNameLineEdit->text();
  
    modif->setName(text);
  
    text = m_ui.modifFormulaLineEdit->text();
  
    modif->setFormula(text);

    // Attention, we have to compute the masses of the modif !

    if (!modif->calculateMasses())
      return false;
  
    // We do not actually care of the targets of the modification. This
    // member datum should be '*' by default anyway.

    //  modif->setTargets("*");
  
    if (!modif->validate())
      return false;

    return true;
  }


  void
  PolymerModificationDlg::modify()
  {
    Polymer *polymer = mp_editorWnd->polymer();

    // There are two ways to perform a modification: either select one
    // modification from the list of available modifications as defined
    // in the polymer chemistry definition, or perform a quick and dirty
    // modification definition in the dialog.

    Modif modif(polymer->polChemDef(), "NOT_SET");
  
    if (m_ui.defineModifGroupBox->isChecked())
      {
	// The user wants to use a self-defined modification.
      
	if(!parseModifDefinition(&modif))
	  {
	    return;
	  }
      }
    else
      {
	// The user should have selected one item from the list of
	// available modifications. Let's get to the modification in
	// question.

	QList<QListWidgetItem *> selectedList = 
	  m_ui.modifListWidget->selectedItems();
  
	if(selectedList.size() != 1)
	  return;
  
	QString text = selectedList.at(0)->text();
	Q_ASSERT(!text.isEmpty());
	//       qDebug() << __FILE__ << __LINE__
	// 		<< "Selected modif:" << text;
      
	// Change modif so that it has its name, and we can ask the
	// polymer chemistry definition to fully qualify it by its name.

	modif.setName(text);
      
	// Find the proper modification in the list of modifs in the
	// polymer chemistry definition and update all the data from the
	// reference one in the polymer chemistry definition.
	if(Modif::isNameInList(text, polymer->polChemDef()->modifList(),
				 &modif) == -1)
	  {
	    QMessageBox::warning(this,
				  tr("massXpert - Polymer Modification"),
				  tr("Failed to find formula(%1) in list.")
				  .arg(modif.name()),
				  QMessageBox::Ok);

	    return;
	  }
      }
  
    // At this point, whatever the way the modification was created, we
    // have it full and working. Use it to perform the modification
    // according to the user's requests.

    if (m_ui.leftEndCheckBox->checkState() == Qt::Checked)
      {
	polymer->setLeftEndModif(modif);
	mp_editorWnd->setWindowModified(true);
      }
  
    if (m_ui.rightEndCheckBox->checkState() == Qt::Checked)
      {
	polymer->setRightEndModif(modif);
	mp_editorWnd->setWindowModified(true);
      }
  
    updateModificationLineEdits();
  
    mp_editorWnd->updatePolymerEndsModifs();

    mp_editorWnd->updateWholeSequenceMasses(true);
    mp_editorWnd->updateSelectedSequenceMasses(true);
  
    return;
  }


  void
  PolymerModificationDlg::unmodify()
  {
    Polymer *polymer = mp_editorWnd->polymer();

    if (m_ui.leftEndCheckBox->checkState() == Qt::Checked)
      {
	polymer->setLeftEndModif();
	mp_editorWnd->setWindowModified(true);
      }
  
    if (m_ui.rightEndCheckBox->checkState() == Qt::Checked)
      {
	polymer->setRightEndModif();
	mp_editorWnd->setWindowModified(true);
      }

    updateModificationLineEdits();

    // Also update the labels of the buttons in the sequence editor
    // window.
    mp_editorWnd->updatePolymerEndsModifs();

    mp_editorWnd->updateWholeSequenceMasses(true);
    mp_editorWnd->updateSelectedSequenceMasses(true);
  }

} // namespace massXpert
