/* 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 "ModifDefDlg.hpp"
#include "../nongui/PolChemDef.hpp"
#include "PolChemDefWnd.hpp"


namespace msxps
{

	namespace massxpert
	{



ModifDefDlg::ModifDefDlg(PolChemDef *polChemDef,
                         PolChemDefWnd *polChemDefWnd,
                         const QString &settingsFilePath)
  : AbstractPolChemDefDependentDlg{polChemDef,
                                   polChemDefWnd,
                                   settingsFilePath,
                                   "ModifDefDlg",
                                   "massXpert: Modification definition"}
{
  Q_ASSERT(polChemDef);
  mp_polChemDef = polChemDef;
  mp_list       = polChemDef->modifListPtr();

  Q_ASSERT(polChemDefWnd);
  mp_polChemDefWnd = polChemDefWnd;

  if(!initialize())
    {
      qDebug() << "Failed to initialize the modif definition window";
    }
}


ModifDefDlg::~ModifDefDlg()
{
}


void
ModifDefDlg::closeEvent([[maybe_unused]] 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.modifPushButton->setChecked(false);

  readSettings();
}


void
ModifDefDlg::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
ModifDefDlg::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
ModifDefDlg::initialize()
{
  m_ui.setupUi(this);

  // Set all the modifs to the list widget.

  for(int iter = 0; iter < mp_list->size(); ++iter)
    {
      Modif *modif = mp_list->at(iter);

      m_ui.modifListWidget->addItem(modif->name());
    }

  readSettings();

  // Make the connections.

  connect(m_ui.addModifPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(addModifPushButtonClicked()));

  connect(m_ui.removeModifPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(removeModifPushButtonClicked()));

  connect(m_ui.moveUpModifPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(moveUpModifPushButtonClicked()));

  connect(m_ui.moveDownModifPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(moveDownModifPushButtonClicked()));

  connect(m_ui.applyModifPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(applyModifPushButtonClicked()));

  connect(m_ui.validatePushButton,
          SIGNAL(clicked()),
          this,
          SLOT(validatePushButtonClicked()));

  connect(m_ui.modifListWidget,
          SIGNAL(itemSelectionChanged()),
          this,
          SLOT(modifListWidgetItemSelectionChanged()));


  return true;
}


void
ModifDefDlg::addModifPushButtonClicked()
{
  // We are asked to add a new modif. We'll add it right after the
  // current item.

  // Returns -1 if the list is empty.
  int index = m_ui.modifListWidget->currentRow();

  Modif *newModif =
    new Modif(mp_polChemDef, tr("Type Name"), tr("Type Formula"));

  mp_list->insert(index, newModif);
  m_ui.modifListWidget->insertItem(index, newModif->name());

  setModified();

  // Needed so that the setCurrentRow() call below actually set the
  // current row!
  if(index <= 0)
    index = 0;

  m_ui.modifListWidget->setCurrentRow(index);

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


void
ModifDefDlg::removeModifPushButtonClicked()
{
  QList<QListWidgetItem *> selectedList = m_ui.modifListWidget->selectedItems();

  if(selectedList.size() != 1)
    return;

  // Get the index of the current modif.
  int index = m_ui.modifListWidget->currentRow();

  // Get a pointer to the modification, as we have to make one
  // check.

  Modif *modif = mp_list->at(index);
  Q_ASSERT(modif);

  // It is essential that we check if the modification being removed
  // is already used or not in a cross-linker, as it would not be
  // possible to tolerate this.

  const QList<CrossLinker *> &list = mp_polChemDef->crossLinkerList();

  for(int iter = 0; iter < list.size(); ++iter)
    {
      CrossLinker *crossLinker = list.at(iter);

      if(crossLinker->hasModif(modif->name()) != -1)
        {
          QString message(tr("A modif with same name is used"
                             " in cross-linker %1.")
                            .arg(crossLinker->name()));

          QMessageBox::warning(
            this, tr("massXpert - Modif definition"), message, QMessageBox::Ok);

          return;
        }
    }

  // At this point we know we can delete the modif, after we have
  // removed it from the modification list of the polymer chemistry
  // definition.
  mp_list->removeAt(index);
  delete modif;

  // And the item.
  QListWidgetItem *item = m_ui.modifListWidget->takeItem(index);
  delete item;

  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 modif that we removed.

  if(m_ui.modifListWidget->count() >= index + 1)
    {
      m_ui.modifListWidget->setCurrentRow(index);
      modifListWidgetItemSelectionChanged();
    }

  // If there are no more items in the list, remove all the items
  // from the isotopeList.

  if(!m_ui.modifListWidget->count())
    {
      clearAllDetails();
    }
}


void
ModifDefDlg::moveUpModifPushButtonClicked()
{
  // Move the current row to one index less.

  // If no modif is selected, just return.

  QList<QListWidgetItem *> selectedList = m_ui.modifListWidget->selectedItems();

  if(selectedList.size() != 1)
    return;

  // Get the index of the modif and the modif itself.
  int index = m_ui.modifListWidget->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.modifListWidget->takeItem(index);

  m_ui.modifListWidget->insertItem(index - 1, item);
  m_ui.modifListWidget->setCurrentRow(index - 1);
  modifListWidgetItemSelectionChanged();

  setModified();
}


void
ModifDefDlg::moveDownModifPushButtonClicked()
{
  // Move the current row to one index less.

  // If no modif is selected, just return.

  QList<QListWidgetItem *> selectedList = m_ui.modifListWidget->selectedItems();

  if(selectedList.size() != 1)
    return;

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

  // If the item is already at bottom of list, do nothing.
  if(index == m_ui.modifListWidget->count() - 1)
    return;

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

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

  setModified();
}


void
ModifDefDlg::applyModifPushButtonClicked()
{
  // We are asked to apply the data for the modif.

  // If no modif is selected, just return.

  QList<QListWidgetItem *> selectedList = m_ui.modifListWidget->selectedItems();

  if(selectedList.size() != 1)
    return;

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

  Modif *modif = mp_list->at(index);

  // We do not want more than one modif by the same name or the same
  // symbol.

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

  QString editFormula = m_ui.formulaLineEdit->text();

  QString editTargets = m_ui.targetLineEdit->text();

  int maxCount = m_ui.maxCountSpinBox->value();

  // If a modif is found in the list with the name string, and that
  // modif is not the one that is current in the modif list, then we
  // are making a double entry, which is not allowed.

  int nameRes = Modif::isNameInList(editName, *mp_list);
  if(nameRes != -1 && nameRes != index)
    {
      QMessageBox::warning(this,
                           tr("massXpert - Modif definition"),
                           tr("A modif with same name exists already."),
                           QMessageBox::Ok);
      return;
    }

  // A modif name cannot have the same name as a crossLinker. This is
  // because the name of the modif cannot clash with the name of a
  // crossLinker when setting the graphical vignette of the
  // modif.
  if(mp_polChemDef->crossLinker(editName))
    {
      QMessageBox::warning(this,
                           tr("massXpert - Modif definition"),
                           tr("The name of the modification is already "
                              "used by a cross-linker."),
                           QMessageBox::Ok);
      return;
    }

  // At this point, validate the formula:

  Formula formula(editFormula);

  if(!formula.validate(mp_polChemDef->atomList()))
    {
      QMessageBox::warning(this,
                           tr("massXpert - Modif definition"),
                           tr("The formula failed to validate."),
                           QMessageBox::Ok);
      return;
    }

  // Validate the max count value.

  if(maxCount <= 0)
    {
      QMessageBox::warning(this,
                           tr("massXpert - Modif definition"),
                           tr("The max count value is invalid."),
                           QMessageBox::Ok);
      return;
    }

  modif->setMaxCount(maxCount);

  // Validate the target list.

  Modif tempModif(*modif);

  tempModif.setTargets(editTargets);

  if(!tempModif.validateTargets())
    {
      QMessageBox::warning(this,
                           tr("massXpert - Modif definition"),
                           tr("The targets string is invalid."),
                           QMessageBox::Ok);
      return;
    }

  modif->setTargets(tempModif.targets());


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

  modif->setName(editName);
  modif->setFormula(editFormula);

  // Update the list widget item.

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

  setModified();
}


bool
ModifDefDlg::validatePushButtonClicked()
{
  QStringList errorList;

  // All we have to do is validate the modif 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
  // modif list and the listwidget.

  int itemCount = m_ui.modifListWidget->count();

  if(itemCount != mp_list->size())
    {
      errorList << QString(
        tr("\nThe number of modifs in the list widget \n"
           "and in the list of modifs is not "
           "identical.\n"));

      QMessageBox::warning(this,
                           tr("massXpert - Modif definition"),
                           errorList.join("\n"),
                           QMessageBox::Ok);
      return false;
    }

  for(int iter = 0; iter < mp_list->size(); ++iter)
    {
      QListWidgetItem *item = m_ui.modifListWidget->item(iter);

      Modif *modif = mp_list->at(iter);

      if(item->text() != modif->name())
        errorList << QString(tr("\nModif at index %1 has not the same\n"
                                "name as the list widget item at the\n"
                                "same index.\n")
                               .arg(iter));

      if(!modif->validate())
        errorList << QString(
          tr("\nModif at index %1  failed to validate.\n").arg(iter));
    }

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

  return true;
}


void
ModifDefDlg::modifListWidgetItemSelectionChanged()
{
  // The modif item has changed. Update the details for the modif.

  // The list is a single-item-selection list.

  QList<QListWidgetItem *> selectedList = m_ui.modifListWidget->selectedItems();

  if(selectedList.size() != 1)
    return;

  // Get the index of the current modif.
  int index = m_ui.modifListWidget->currentRow();

  Modif *modif = mp_list->at(index);
  Q_ASSERT(modif);

  // Set the data of the modif to their respective widgets.
  updateModifDetails(modif);
}


void
ModifDefDlg::updateModifDetails(Modif *modif)
{
  if(modif)
    {
      m_ui.nameLineEdit->setText(modif->name());
      m_ui.formulaLineEdit->setText(modif->formula());
      m_ui.targetLineEdit->setText(modif->targets());
      m_ui.maxCountSpinBox->setValue(modif->maxCount());
    }
  else
    clearAllDetails();
}


void
ModifDefDlg::clearAllDetails()
{
  m_ui.nameLineEdit->setText("");
  m_ui.formulaLineEdit->setText("");
  m_ui.targetLineEdit->setText("");
  m_ui.maxCountSpinBox->setValue(1);
}


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

} // namespace massxpert

} // namespace msxps
