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


/////////////////////// Qt includes
#include <QMessageBox>


/////////////////////// Local includes
#include <massxpert/gui/MonomerDefDlg.hpp>
#include <massxpert/nongui/PolChemDef.hpp>
#include <massxpert/gui/PolChemDefWnd.hpp>


namespace msXpSmassXpert
{

MonomerDefDlg::MonomerDefDlg(PolChemDef *polChemDef,
                             PolChemDefWnd *polChemDefWnd,
                             const QString &settingsFilePath)
  : AbstractPolChemDefDependentDlg{polChemDef,
                                   polChemDefWnd,
                                   settingsFilePath,
                                   "MonomerDefDlg",
                                   "massXpert: Monomer definition"}
{
  mp_list = polChemDef->monomerListPtr();

  if(!initialize())
    qFatal(
      "Fatal error at %s@%d. Failed to initialize the %s window. Program "
      "aborted.",
      __FILE__,
      __LINE__,
      m_wndTypeName.toLatin1().data());
}


MonomerDefDlg::~MonomerDefDlg()
{
}


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);

  writeSettings();
}


void
MonomerDefDlg::readSettings()
{
  QSettings settings(m_settingsFilePath, QSettings::IniFormat);

  settings.beginGroup(m_wndTypeName);
  restoreGeometry(settings.value("geometry").toByteArray());
  m_ui.splitter->restoreState(settings.value("splitter").toByteArray());
  settings.endGroup();
}


void
MonomerDefDlg::writeSettings()
{

  QSettings settings(m_settingsFilePath, QSettings::IniFormat);

  settings.beginGroup(m_wndTypeName);
  restoreGeometry(settings.value("geometry").toByteArray());
  settings.setValue("splitter", m_ui.splitter->saveState());
  settings.endGroup();
}


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());
    }

  readSettings();

  // 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:

  msXpSlibmass::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();

  // Note that this should not occur, I gess, but one I got this crash, so
  // test that the returned index is not -1.
  if(index >= 0)
    {
      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("");
}


// 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<msXpSlibmass::Atom *> &atomList = mp_polChemDef->atomList();

  msXpSlibmass::Formula formula(string);

  msXpSlibmass::Ponderable ponderable(0, 0);

  if(!formula.accountMasses(atomList, &ponderable))
    {
      m_ui.monoMassLineEdit->setText(tr("Bad formula"));
      m_ui.avgMassLineEdit->setText(tr("Bad formula"));

      return;
    }

  m_ui.monoMassLineEdit->setText(ponderable.monoString(msXpS::ATOM_DEC_PLACES));

  m_ui.avgMassLineEdit->setText(ponderable.avgString(msXpS::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 = msXpS::MassType::MASS_MONO;
  else
    monoOrAvg = msXpS::MassType::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 msXpSmassXpert
