/* 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/CrossLinkerDefDlg.hpp>
#include <massxpert/nongui/PolChemDef.hpp>
#include <massxpert/gui/PolChemDefWnd.hpp>


namespace msXpSmassXpert
{

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

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


CrossLinkerDefDlg::~CrossLinkerDefDlg()
{
}

void
CrossLinkerDefDlg::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.crossLinkerPushButton->setChecked(false);

  writeSettings();
}


void
CrossLinkerDefDlg::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
CrossLinkerDefDlg::writeSettings()
{
  QSettings settings(m_settingsFilePath, QSettings::IniFormat);

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


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

  // Set all the crossLinkers to the list widget.

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

      m_ui.crossLinkerListWidget->addItem(crossLinker->name());
    }

  readSettings();

  populateAvailableModifList();

  // Make the connections.

  connect(m_ui.addCrossLinkerPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(addCrossLinkerPushButtonClicked()));

  connect(m_ui.removeCrossLinkerPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(removeCrossLinkerPushButtonClicked()));

  connect(m_ui.moveUpCrossLinkerPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(moveUpCrossLinkerPushButtonClicked()));

  connect(m_ui.moveDownCrossLinkerPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(moveDownCrossLinkerPushButtonClicked()));

  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.applyCrossLinkerPushButton,
          SIGNAL(clicked()),
          this,
          SLOT(applyCrossLinkerPushButtonClicked()));

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

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

  connect(m_ui.crossLinkerListWidget,
          SIGNAL(itemSelectionChanged()),
          this,
          SLOT(crossLinkerListWidgetItemSelectionChanged()));

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

  return true;
}


bool
CrossLinkerDefDlg::populateAvailableModifList()
{
  // The first item should be an empty item in case no modification
  // is present in the cross-linker.

  m_ui.modifNameComboBox->addItem("");

  for(int iter = 0; iter < mp_polChemDef->modifList().size(); ++iter)
    {
      Modif *modif = mp_polChemDef->modifList().at(iter);
      Q_ASSERT(modif);

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

  return true;
}


void
CrossLinkerDefDlg::addCrossLinkerPushButtonClicked()
{
  // We are asked to add a new crossLinker. We'll add it right after the
  // current item.

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

  CrossLinker *newCrossLinker =
    new CrossLinker(mp_polChemDef, tr("Type Name"), tr("Type Formula"));

  mp_list->insert(index, newCrossLinker);
  m_ui.crossLinkerListWidget->insertItem(index, newCrossLinker->name());

  setModified();

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

  m_ui.crossLinkerListWidget->setCurrentRow(index);

  // Erase cleaveRule data that might be left over by precedent current
  // crossLinker.
  updateModifDetails(0);

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


void
CrossLinkerDefDlg::removeCrossLinkerPushButtonClicked()
{
  QList<QListWidgetItem *> selectedList =
    m_ui.crossLinkerListWidget->selectedItems();

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

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

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

  CrossLinker *crossLinker = mp_list->takeAt(index);
  Q_ASSERT(crossLinker);
  delete crossLinker;

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

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

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

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


void
CrossLinkerDefDlg::moveUpCrossLinkerPushButtonClicked()
{
  // Move the current row to one index less.

  // If no crossLinker is selected, just return.

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

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

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

  m_ui.crossLinkerListWidget->insertItem(index - 1, item);
  m_ui.crossLinkerListWidget->setCurrentRow(index - 1);
  crossLinkerListWidgetItemSelectionChanged();

  setModified();
}


void
CrossLinkerDefDlg::moveDownCrossLinkerPushButtonClicked()
{
  // Move the current row to one index less.

  // If no crossLinker is selected, just return.

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

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

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

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

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

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

  setModified();
}


void
CrossLinkerDefDlg::addModifPushButtonClicked()
{
  // We are asked to add a new modif. We'll add it right after the
  // current item. Note however, that one crossLinker has to be
  // selected.

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

  if(selectedList.size() != 1)
    {
      QMessageBox::information(this,
                               tr("massXpert - CrossLinker definition"),
                               tr("Please, select a crossLinker first."),
                               QMessageBox::Ok);
      return;
    }

  // Get the index of the current crossLinker so that we know to which
  // crossLinker we'll add the modif.
  int index = m_ui.crossLinkerListWidget->currentRow();

  // What's the actual crossLinker?
  CrossLinker *crossLinker = mp_list->at(index);
  Q_ASSERT(crossLinker);

  // Allocate the new modif.
  Modif *newModif = new Modif(mp_polChemDef, tr("Select modification"));

  // Get the row index of the current modif item. Returns -1 if the
  // list is empty.
  index = m_ui.modifListWidget->currentRow();

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

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

  crossLinker->modifList().insert(index, newModif);

  m_ui.modifListWidget->setCurrentRow(index);

  setModified();

  // Set the focus to the lineEdit that holds the mass of the modif.
  m_ui.modifNameComboBox->setFocus();
}


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

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


  // Get the index of the current crossLinker so that we know from
  // which crossLinker we'll remove the modif.
  int index = m_ui.crossLinkerListWidget->currentRow();

  CrossLinker *crossLinker = mp_list->at(index);
  Q_ASSERT(crossLinker);

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

  // First remove the item from the listwidget because that will have
  // modifListWidgetItemSelectionChanged() triggered and we have to
  // have the item in the modif list in the crossLinker! Otherwise a crash
  // occurs.
  QListWidgetItem *item = m_ui.modifListWidget->takeItem(index);
  delete item;

  // Remove the modif from the crossLinker proper.

  QList<Modif *> modifList = crossLinker->modifList();

  Modif *modif = modifList.at(index);

  crossLinker->modifList().removeAt(index);
  delete modif;

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

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

  // If there are no more items in the modif list, remove all the
  // details.

  if(!m_ui.modifListWidget->count())
    {
      updateModifDetails(0);
    }
  else
    {
    }

  setModified();
}


void
CrossLinkerDefDlg::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 crossLinker to which the modif belongs.
  int index                = m_ui.crossLinkerListWidget->currentRow();
  CrossLinker *crossLinker = mp_list->at(index);

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

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

  // Get the modif itself from the crossLinker.
  Modif *modif = crossLinker->modifList().at(index);

  crossLinker->modifList().removeAt(index);
  crossLinker->modifList().insert(index - 1, modif);

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

  setModified();
}


void
CrossLinkerDefDlg::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 crossLinker to which the modif belongs.
  int index                = m_ui.crossLinkerListWidget->currentRow();
  CrossLinker *crossLinker = mp_list->at(index);

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

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

  // Get the modif itself from the crossLinker.
  Modif *modif = crossLinker->modifList().at(index);

  crossLinker->modifList().removeAt(index);
  crossLinker->modifList().insert(index + 1, modif);

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

  setModified();
}


void
CrossLinkerDefDlg::applyCrossLinkerPushButtonClicked()
{
  // We are asked to apply the data for the crossLinker.

  // If no crossLinker is selected, just return.

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

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

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

  CrossLinker *crossLinker = mp_list->at(index);

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

  bool wasEditFormulaEmpty = false;


  QString editName    = m_ui.nameLineEdit->text();
  QString editFormula = m_ui.formulaLineEdit->text();
  if(editFormula.isEmpty())
    {
      editFormula = "+Nul";

      wasEditFormulaEmpty = true;
    }

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

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

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

  msXpSlibmass::Formula formula(editFormula);

  if(!formula.validate(mp_polChemDef->atomList()))
    {
      if(wasEditFormulaEmpty)
        {
          QMessageBox::warning(
            this,
            tr("massXpert - CrossLinker definition"),
            tr("The formula is empty, please enter a formula "
               "like '-H+H' if no reaction is required."),
            QMessageBox::Ok);
        }
      else
        {
          QMessageBox::warning(this,
                               tr("massXpert - CrossLinker definition"),
                               tr("The formula failed to validate."),
                               QMessageBox::Ok);
        }

      return;
    }

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

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

  // Update the list widget item.

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

  setModified();
}


void
CrossLinkerDefDlg::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 crossLinker to which the modif belongs.
  int index                = m_ui.crossLinkerListWidget->currentRow();
  CrossLinker *crossLinker = mp_list->at(index);

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

  // Get the modif itself from the crossLinker.
  Modif *modif = crossLinker->modifList().at(index);

  QString modifName = m_ui.modifNameComboBox->currentText();

  // Make sure the modification is known to the polymer chemistry
  // definition.

  Modif localModif = Modif(mp_polChemDef, "NOT_SET", "NOT_SET");

  if(!mp_polChemDef->modif(modifName, &localModif))
    {
      QMessageBox::warning(this,
                           tr("massXpert - CrossLinker definition"),
                           tr("The modification is not known to the "
                              "polymer chemistry definition."),
                           QMessageBox::Ok);
      return;
    }

  modif->mold(localModif);

  // Update the list widget item.

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

  setModified();
}


bool
CrossLinkerDefDlg::validatePushButtonClicked()
{
  QStringList errorList;

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

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

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

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

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

      CrossLinker *crossLinker = mp_list->at(iter);

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

      if(!crossLinker->validate())
        errorList << QString(
          tr("\nCrossLinker at index %1 failed "
             "to validate.\n"
             "Please, make sure that there are either no"
             " or at least two modifications for the cross-link.\n")
            .arg(iter));
    }

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

  return true;
}


void
CrossLinkerDefDlg::crossLinkerListWidgetItemSelectionChanged()
{
  // The crossLinker item has changed. Empty the modif list and update its
  // contents. Update the details for the crossLinker.

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

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

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

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

  CrossLinker *crossLinker = mp_list->at(index);
  Q_ASSERT(crossLinker);

  // Set the data of the crossLinker to their respective widgets.
  updateCrossLinkerIdentityDetails(crossLinker);

  // The list of modifs
  m_ui.modifListWidget->clear();

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

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

  if(!m_ui.modifListWidget->count())
    updateModifDetails(0);
  else
    {
      // And now select the first row in the modif list widget.
      m_ui.modifListWidget->setCurrentRow(0);
    }
}


void
CrossLinkerDefDlg::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 crossLinker.
  int index = m_ui.crossLinkerListWidget->currentRow();

  // Find the modif object in the list of modifs.
  CrossLinker *crossLinker = mp_list->at(index);
  Q_ASSERT(crossLinker);

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

  // Get the modif that is currently selected from the crossLinker's list
  // of modifs.
  Modif *modif = crossLinker->modifList().at(index);
  Q_ASSERT(modif);

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


void
CrossLinkerDefDlg::updateCrossLinkerIdentityDetails(CrossLinker *crossLinker)
{
  if(crossLinker)
    {
      m_ui.nameLineEdit->setText(crossLinker->name());
      m_ui.formulaLineEdit->setText(crossLinker->formula());
    }
  else
    {
      m_ui.nameLineEdit->setText("");
      m_ui.formulaLineEdit->setText("");
    }
}


void
CrossLinkerDefDlg::updateModifDetails(Modif *modif)
{
  if(modif)
    {
      int index = m_ui.modifNameComboBox->findText(modif->name());

      // The name might be tr("Select modif") if the modif was just
      // created(see the function to add a modif to a
      // cross-linker), thus we cannot take for granted that we'll
      // find the modif in the comboBox !
      //	Q_ASSERT(index >=  0);
      if(index >= 0)
        m_ui.modifNameComboBox->setCurrentIndex(index);
      else
        // The first item is an empty item.
        m_ui.modifNameComboBox->setCurrentIndex(0);
    }
  else
    {
      // The first item is an empty item.
      m_ui.modifNameComboBox->setCurrentIndex(0);
    }
}


void
CrossLinkerDefDlg::clearAllDetails()
{
  m_ui.nameLineEdit->setText("");
  m_ui.formulaLineEdit->setText("");

  m_ui.modifNameComboBox->setCurrentIndex(0);
}


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

} // namespace msXpSmassXpert
