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

   http://www.filomace.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 "monomerDefDlg.hpp"
#include "polChemDef.hpp"
#include "polChemDefWnd.hpp"


namespace massXpert
{

  MonomerDefDlg::MonomerDefDlg(PolChemDef *polChemDef, 
				PolChemDefWnd *polChemDefWnd)
  {
    Q_ASSERT(polChemDef);
    mp_polChemDef = polChemDef;
    mp_list = polChemDef->monomerListPtr();
  
    Q_ASSERT(polChemDefWnd);
    mp_polChemDefWnd = polChemDefWnd;
  
    if (!initialize())
      {
	qDebug() << "Failed to initialize the monomer definition window";
      }
  }


  void 
  MonomerDefDlg::closeEvent(QCloseEvent *event)
  {  
    // No real close, because we did not ask that
    // close==destruction. Thus we only hide the dialog remembering its
    // position and size.
  
  
    mp_polChemDefWnd->m_ui.monomerPushButton->setChecked(false);

    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
  
    settings.beginGroup("monomer_def_dlg");

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

    settings.setValue("splitter", m_ui.splitter->saveState());

    settings.endGroup();
  }

  

  MonomerDefDlg::~MonomerDefDlg()
  {
  }

  
  bool
  MonomerDefDlg::initialize()
  {
    m_ui.setupUi(this);

    // Set all the monomers to the list widget.

    for (int iter = 0; iter < mp_list->size(); ++iter)
      {
	Monomer *monomer = mp_list->at(iter);
      
	m_ui.monomerListWidget->addItem(monomer->name());
      }

    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
  
    settings.beginGroup("monomer_def_dlg");

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

    m_ui.splitter->restoreState(settings.value("splitter").toByteArray());
    
    settings.endGroup();


    // Get the monomer code length and create a validator for use later.
  
    m_ui.codeLengthSpinBox->setValue(mp_polChemDef->codeLength());
  
    QString regExp = 
      QString("[A-Z][a-z]{0,%1}").arg(mp_polChemDef->codeLength() - 1);
  
    QRegExp codeRegExp(regExp);
    QValidator *validator = new QRegExpValidator(codeRegExp, this);
  
    m_ui.codeLineEdit->setValidator(validator);


    // Make the connections.

    connect(m_ui.addMonomerPushButton, 
	     SIGNAL(clicked()),
	     this, 
	     SLOT(addMonomerPushButtonClicked()));
  
    connect(m_ui.removeMonomerPushButton, 
	     SIGNAL(clicked()),
	     this, 
	     SLOT(removeMonomerPushButtonClicked()));
  
    connect(m_ui.moveUpMonomerPushButton, 
	     SIGNAL(clicked()),
	     this, 
	     SLOT(moveUpMonomerPushButtonClicked()));
  
    connect(m_ui.moveDownMonomerPushButton, 
	     SIGNAL(clicked()),
	     this, 
	     SLOT(moveDownMonomerPushButtonClicked()));
  
    connect(m_ui.applyMonomerPushButton, 
	     SIGNAL(clicked()),
	     this, 
	     SLOT(applyMonomerPushButtonClicked()));

    connect(m_ui.formulaLineEdit,
	    SIGNAL(textChanged(const QString &)),
	    this,
	    SLOT(formulaLineEditTextChanged(const QString &)));
      
    connect(m_ui.validatePushButton, 
	     SIGNAL(clicked()),
	     this, 
	     SLOT(validatePushButtonClicked()));

    connect(m_ui.monomerListWidget, 
	     SIGNAL(itemSelectionChanged()),
	     this, 
	     SLOT(monomerListWidgetItemSelectionChanged()));
  
    connect(m_ui.codeLengthSpinBox,
	     SIGNAL(valueChanged(int)),
	     this,
	     SLOT(codeLengthSpinBoxValueChanged(int)));

    connect(m_ui.calculateMassDifferencesPushButton, 
	    SIGNAL(clicked()),
	    this, 
	    SLOT(calculateMassDifferences()));
    
    return true;
  }


  void 
  MonomerDefDlg::addMonomerPushButtonClicked()
  {
    // We are asked to add a new monomer. We'll add it right after the
    // current item.
  
    // Returns -1 if the list is empty.
    int index = m_ui.monomerListWidget->currentRow();
  
    Monomer *newMonomer = new Monomer(mp_polChemDef,
				       tr("Type Name"),
				       tr("Type Code"),
				       tr("Type Formula"));
  
    mp_list->insert(index, newMonomer);
    m_ui.monomerListWidget->insertItem(index, newMonomer->name());

    setModified();
  
    // Needed so that the setCurrentRow() call below actually set the
    // current row!
    if (index <= 0)
      index = 0;
  
    m_ui.monomerListWidget->setCurrentRow(index);

    // Set the focus to the lineEdit that holds the name of the monomer.
    m_ui.nameLineEdit->setFocus();
    m_ui.nameLineEdit->selectAll();
  }


  void 
  MonomerDefDlg::removeMonomerPushButtonClicked()
  {
    QList<QListWidgetItem *> selectedList = 
      m_ui.monomerListWidget->selectedItems();
  
    if (selectedList.size() != 1)
      return;

    // Get the index of the current monomer.
    int index = m_ui.monomerListWidget->currentRow();
  
    QListWidgetItem *item = m_ui.monomerListWidget->takeItem(index);
    delete item;

    Monomer *monomer = mp_list->takeAt(index);
    Q_ASSERT(monomer);
    delete monomer;
  
    setModified();
  
    // If there are remaining items, we want to set the next item the
    // currentItem. If not, then, the currentItem should be the one
    // preceding the monomer that we removed.

    if (m_ui.monomerListWidget->count() >= index + 1)
      {
	m_ui.monomerListWidget->setCurrentRow(index);
	monomerListWidgetItemSelectionChanged();
      }
  
    // If there are no more items in the list, remove all the items
    // from the isotopeList.
  
    if (!m_ui.monomerListWidget->count())
      {
	clearAllDetails();
      }
  }


  void 
  MonomerDefDlg::moveUpMonomerPushButtonClicked()
  {
    // Move the current row to one index less.

    // If no monomer is selected, just return.

    QList<QListWidgetItem *> selectedList = 
      m_ui.monomerListWidget->selectedItems();
  
    if (selectedList.size() != 1)
      return;

    // Get the index of the monomer and the monomer itself. 
    int index = m_ui.monomerListWidget->currentRow();

    // If the item is already at top of list, do nothing.
    if (!index)
      return;

    mp_list->move(index, index - 1);

    QListWidgetItem *item = m_ui.monomerListWidget->takeItem(index);

    m_ui.monomerListWidget->insertItem(index - 1, item);
    m_ui.monomerListWidget->setCurrentRow(index - 1);
    monomerListWidgetItemSelectionChanged();

    setModified();
  }


  void 
  MonomerDefDlg::moveDownMonomerPushButtonClicked()
  {
    // Move the current row to one index less.

    // If no monomer is selected, just return.

    QList<QListWidgetItem *> selectedList = 
      m_ui.monomerListWidget->selectedItems();
  
    if (selectedList.size() != 1)
      return;

    // Get the index of the monomer and the monomer itself. 
    int index = m_ui.monomerListWidget->currentRow();
  
    // If the item is already at bottom of list, do nothing.
    if (index == m_ui.monomerListWidget->count() - 1)
      return;

    mp_list->move(index, index + 1);

    QListWidgetItem *item = m_ui.monomerListWidget->takeItem(index);
    m_ui.monomerListWidget->insertItem(index + 1, item);
    m_ui.monomerListWidget->setCurrentRow(index + 1);
    monomerListWidgetItemSelectionChanged();

    setModified();
  }


  void 
  MonomerDefDlg::applyMonomerPushButtonClicked()
  {
    // We are asked to apply the data for the monomer.

    // If no monomer is selected, just return.

    QList<QListWidgetItem *> selectedList = 
      m_ui.monomerListWidget->selectedItems();
  
    if (selectedList.size() != 1)
      return;

    // Get the index of the current monomer item.
    int index = m_ui.monomerListWidget->currentRow();

    Monomer *monomer = mp_list->at(index);
  
    // We do not want more than one monomer by the same name or the same
    // symbol.

    QString editName = m_ui.nameLineEdit->text();

    // The syntax [A-Z][a-z]* is automatically validated using the
    // validator(see initialize()).
    QString editCode = m_ui.codeLineEdit->text();

    QString editFormula = m_ui.formulaLineEdit->text();
  
    // If a monomer is found in the list with any of these two strings,
    // and that monomer is not the one that is current in the monomer list,
    // then we are making a double entry, which is not allowed.

    int nameRes = Monomer::isNameInList(editName, *mp_list);
    if (nameRes != -1 && nameRes != index)
      {
	QMessageBox::warning(this, 
			      tr("massXpert - Monomer definition"),
			      tr("A monomer with same name exists already."),
			      QMessageBox::Ok);
	return;
      }
  
    int codeRes = Monomer::isCodeInList(editCode, *mp_list);
    if (codeRes != -1 && codeRes != index)
      {
	QMessageBox::warning(this, 
			      tr("massXpert - Monomer definition"),
			      tr("A monomer with same code exists already."),
			      QMessageBox::Ok);
	return;
      }
  
    // At this point, validate the formula:
  
    Formula formula(editFormula);
  
    if (!formula.validate(mp_polChemDef->atomList()))
      {
	QMessageBox::warning(this, 
			      tr("massXpert - Monomer definition"),
			      tr("The formula failed to validate."),
			      QMessageBox::Ok);
	return;
      }

    // Finally we can update the monomer's data:

    monomer->setName(editName);
    monomer->setCode(editCode);
    monomer->setFormula(editFormula);
  
    // Update the list widget item.

    QListWidgetItem *item = m_ui.monomerListWidget->currentItem();
    item->setData(Qt::DisplayRole, monomer->name());

    setModified();
  }


  bool
  MonomerDefDlg::validatePushButtonClicked()
  {
    QStringList errorList;
  
    // All we have to do is validate the monomer definition. For that we'll
    // go in the listwidget items one after the other and make sure that
    // everything is fine and that colinearity is perfect between the
    // monomer list and the listwidget.
  
    int itemCount = m_ui.monomerListWidget->count();
  
    if (itemCount != mp_list->size())
      {
	errorList << QString(tr("\nThe number of monomers in the "
				  "list widget \n"
				  "and in the list of monomers is "
				  "not identical.\n"));
      
	QMessageBox::warning(this, 
			      tr("massXpert - Monomer definition"),
			      errorList.join("\n"),
			      QMessageBox::Ok);
	return false;
      }

    for (int iter = 0; iter < mp_list->size(); ++iter)
      {
	QListWidgetItem *item = m_ui.monomerListWidget->item(iter);
      
	Monomer *monomer = mp_list->at(iter);
      
	if(item->text() != monomer->name())
	  errorList << QString(tr("\nMonomer at index %1 has not the same\n"
				    "name as the list widget item at the\n"
				    "same index.\n")
				.arg(iter));
      
	if(!monomer->validate())
	  errorList << QString(tr("\nMonomer at index %1  failed to validate.\n")
				.arg(iter));
      }

    if (errorList.size())
      {
	QMessageBox::warning(this, 
			      tr("massXpert - Monomer definition"),
			      errorList.join("\n"),
			      QMessageBox::Ok);
	return false;
      }
    else
      {
	QMessageBox::warning(this, 
			      tr("massXpert - Monomer definition"),
			     ("Validation: success\n"),
			      QMessageBox::Ok);
      }
  
    return true;
  }


  void 
  MonomerDefDlg::monomerListWidgetItemSelectionChanged()
  {
    // The monomer item has changed. Update the details for the monomer.

    // The list is a single-item-selection list.
  
    QList<QListWidgetItem *> selectedList = 
      m_ui.monomerListWidget->selectedItems();
  
    if (selectedList.size() != 1)
      return;

    // Get the index of the current monomer.
    int index = m_ui.monomerListWidget->currentRow();
  
    Monomer *monomer = mp_list->at(index);
    Q_ASSERT(monomer);
  
    // Set the data of the monomer to their respective widgets.
    updateMonomerDetails(monomer);
  }


  void 
  MonomerDefDlg::codeLengthSpinBoxValueChanged(int value)
  {
    // We have to update the validator for the monomer code line edit.

    if (value < 1)
      return;

    // We need to update the monomer code RegExp validator with the new
    // codeLength value.

    QString regExp = QString("[A-Z][a-z]{0,%1}").arg(value - 1);
    //    qDebug() << "new regExp:" << regExp;
  
    QRegExp codeRegExp(regExp);
    QValidator *validator = new QRegExpValidator(codeRegExp, this);
  
    m_ui.codeLineEdit->setValidator(validator);

    // And now inform the whole polymer definition that the codeLength
    // value has changed.

    mp_polChemDef->setCodeLength(value);
  }


  void
  MonomerDefDlg::updateMonomerDetails(Monomer *monomer)
  {
    if (monomer)
      {
	m_ui.nameLineEdit->setText(monomer->name());
	m_ui.codeLineEdit->setText(monomer->code());
	m_ui.formulaLineEdit->setText(monomer->formula());
      }
    else
      {
	m_ui.nameLineEdit->setText("");
	m_ui.codeLineEdit->setText("");
	m_ui.formulaLineEdit->setText("");
      } 
  }


  void
  MonomerDefDlg::clearAllDetails()
  {
    m_ui.nameLineEdit->setText("");
    m_ui.codeLineEdit->setText("");
    m_ui.formulaLineEdit->setText("");
  }


  void 
  MonomerDefDlg::setModified()
  {
    mp_polChemDefWnd->setWindowModified(true); 
  }


  // VALIDATION
  bool
  MonomerDefDlg::validate()
  {
    return validatePushButtonClicked();
  }

  void
  MonomerDefDlg::formulaLineEditTextChanged(const QString &string)
  {
    // Each time the formula of the monomer is edited, we compute the
    // masses of the formula. If the computation failed, we set "Bad
    // formula" in the line edit widgets of the masses.

    const QList<Atom *> &atomList = mp_polChemDef->atomList();
    
    Formula formula(string);
    
    Ponderable ponderable (0,0);
        
    if (!formula.accountMasses(atomList, &ponderable))
      {
	m_ui.monoMassLineEdit->setText(tr("Bad formula"));
	m_ui.avgMassLineEdit->setText(tr("Bad formula"));
	
	return;
      }

    Application *application = static_cast<Application *>(qApp);
    QLocale locale = application->locale();

    m_ui.monoMassLineEdit->
      setText(ponderable.mono(locale, MXP_ATOM_DEC_PLACES));

    m_ui.avgMassLineEdit->
      setText(ponderable.avg(locale, MXP_ATOM_DEC_PLACES));
  }
  

  void
  MonomerDefDlg::calculateMassDifferences()
  {
    // Allocate a new QStringList object in which all the mass
    // differences between any two monomers in the definitions are
    // below the threshold set into the thresholdLineEdit.

    bool ok = false;
    
    double threshold = m_ui.thresholdLineEdit->text().toDouble(&ok);
    
    if (!threshold && !ok)
      {
	QMessageBox::warning(this, 
			     tr("massXpert - Monomer definition"),
			     tr("Threshold value is not valid"),
			     QMessageBox::Ok);
	return;
      }
    
    bool isMonoMass = m_ui.monoMassRadioButton->isChecked();
    
    int monoOrAvg;
    
    if (isMonoMass)
      monoOrAvg = MXT_MASS_MONO;
    else
      monoOrAvg = MXT_MASS_AVG;
    
    QStringList *diffList = 
      mp_polChemDef->differenceBetweenMonomers(threshold, monoOrAvg);
    
    if (!diffList)
      return;
    
    QMessageBox::information(this, 
			     tr("massXpert - Monomer definition"),
			     diffList->join("\n"),
			     QMessageBox::Ok);
    
    delete diffList;
    
    return;
  }
  

} // namespace massXpert
