/* massXpert - the true massist's program.
   --------------------------------------
   Copyright(C) 2006-2013 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>
#include <QCloseEvent>
#include <QDebug>


/////////////////////// Local includes
#include "mzLabFormulaBasedActionsDlg.hpp"
#include "mzLabInputOligomerTableViewDlg.hpp"
#include "mzLabWnd.hpp"
#include "application.hpp"
#include "ionizeRule.hpp"


namespace massXpert
{

  MzLabFormulaBasedActionsDlg::MzLabFormulaBasedActionsDlg
  (QWidget *parent) : QDialog(parent)
  {
    Q_ASSERT(parent);

    mp_mzLabWnd = static_cast<MzLabWnd *>(parent);

    m_ui.setupUi(this);

    setWindowTitle(tr("massXpert: mz Lab - Formula-based Actions"));
    
    m_ui.incrementChargeSpinBox->setRange(-1000000000, 1000000000);

    PolChemDef *polChemDef = mp_mzLabWnd->polChemDef();
    
    IonizeRule ionizeRule = polChemDef->ionizeRule();
    
    m_ui.reIonizationFormulaLineEdit->setText(ionizeRule.formula());
    m_ui.reIonizationChargeSpinBox->setValue(ionizeRule.charge());
    m_ui.reIonizationLevelSpinBox->setValue(ionizeRule.level());

    connect(m_ui.applyFormulaPushButton,
            SIGNAL(clicked()),
            this,
            SLOT(applyFormulaPushButton()));

    connect(m_ui.incrementChargePushButton,
            SIGNAL(clicked()),
            this,
            SLOT(incrementChargePushButton()));

    connect(m_ui.reionizePushButton,
            SIGNAL(clicked()),
            this,
            SLOT(reionizePushButton()));

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

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

    settings.endGroup();

}
  

  MzLabFormulaBasedActionsDlg::~MzLabFormulaBasedActionsDlg()
  {
  }


  void
  MzLabFormulaBasedActionsDlg::closeEvent(QCloseEvent *event)
  {
    QSettings settings 
     (static_cast<Application *>(qApp)->configSettingsFilePath(), 
       QSettings::IniFormat);
    
    settings.beginGroup("mz_lab_wnd_formula_based_actions");
    
    settings.setValue("geometry", saveGeometry());
    
    settings.endGroup();

    QDialog::closeEvent(event);
  }


  void
  MzLabFormulaBasedActionsDlg::applyFormulaPushButton()
  {
    // The actual work of doing the calculation is performed by the
    // MzLabInputOligomerTableViewDlg itself. So we have to get a
    // pointer to that dialog window. But first, check if the mass
    // entered in the line edit is correct.

    QString text = m_ui.formulaLineEdit->text();
    if (text.isEmpty())
      {
	QMessageBox::warning(this,
			      tr("massXpert: mz Lab"),
			      tr("%1@%2\n"
				  "Please, enter a valid formula.")
			      .arg(__FILE__)
			      .arg(__LINE__));
	return;
      }
    
    // Further, we have to get a pointer to the polymer chemistry
    // definition in use in this mzLab, because we need to validate
    // the formula.

    PolChemDef * polChemDef = mp_mzLabWnd->polChemDef();

    Formula formula(text);
    
    if (!formula.validate(polChemDef->atomList()))
      {
	QMessageBox::warning(this,
			      tr("massXpert: mz Lab"),
			      tr("%1@%2\n"
				  "The formula '%3' is not valid.")
			      .arg(__FILE__)
			      .arg(__LINE__)
			      .arg(formula.text()));
	return;
      }


    // Get the pointer to the input list dialog window.

    MzLabInputOligomerTableViewDlg *dlg = 0;
    dlg = mp_mzLabWnd->inputListDlg();
    if (!dlg)
      {
        QMessageBox::warning(this,
                             tr("massXpert: mz Lab"),
                             tr("%1@%2\n"
                                "Please, select one input list first.")
                             .arg(__FILE__)
                             .arg(__LINE__));
	return;
      }

    // Is the calculation to be performed inside the input list dialog
    // window, or are we going to create a new mz list with the
    // results of that calculation?
    bool inPlace = mp_mzLabWnd->inPlaceCalculation();
    
    // Finally actually have the calculation performed by the mz input
    // list dialog window.
    dlg->applyFormula(formula, inPlace);
  }


 void
  MzLabFormulaBasedActionsDlg::incrementChargePushButton()
  {
    // The actual work of doing the calculation is performed by the
    // MzLabInputOligomerTableViewDlg itself. So we have to get a
    // pointer to that dialog window. But first, check if the threshold
    // entered in the line edit is empty/correct or not.

    int increment = m_ui.incrementChargeSpinBox->value();

    if (!increment)
      {
	QMessageBox::warning 
	 (this, 
	   tr("massXpert: mz Lab"),
	   tr("%1@%2\n"
	       "Please, enter a valid increment.")
	   .arg(__FILE__)
	   .arg(__LINE__),
	   QMessageBox::Ok);

	return;
      }

    // Get the pointer to the input list dialog window.

    MzLabInputOligomerTableViewDlg *dlg = 0;
    dlg = mp_mzLabWnd->inputListDlg();
    if (!dlg)
      {
        QMessageBox::warning(this,
                             tr("massXpert: mz Lab"),
                             tr("%1@%2\n"
                                "Please, select one input list first.")
                             .arg(__FILE__)
                             .arg(__LINE__));
	return;
      }
    
    // Is the calculation to be performed inside the input list dialog
    // window, or are we going to create a new mz list with the
    // results of that calculation?
    bool inPlace = mp_mzLabWnd->inPlaceCalculation();

    // Finally actually have the calculation performed by the mz input
    // list dialog window.
    dlg->applyChargeIncrement(increment, inPlace);
  }


 void
  MzLabFormulaBasedActionsDlg::reionizePushButton()
  {
    // The actual work of doing the calculation is performed by the
    // MzLabInputOligomerTableViewDlg itself. So we have to get a
    // pointer to that dialog window. But first, check if the threshold
    // entered in the line edit is empty/correct or not.

    IonizeRule ionizeRule;
    
    ionizeRule.setFormula(m_ui.reIonizationFormulaLineEdit->text());
    ionizeRule.setCharge(m_ui.reIonizationChargeSpinBox->value());
    ionizeRule.setLevel(m_ui.reIonizationLevelSpinBox->value());

    // Further, we have to get a pointer to the polymer chemistry
    // definition in use in this mzLab, because we need to validate
    // the ionization rule.

    PolChemDef * polChemDef = mp_mzLabWnd->polChemDef();

    if (!ionizeRule.validate(polChemDef->atomList()))
      {
	QMessageBox::warning 
	 (this, 
	   tr("massXpert: mz Lab"),
	   tr("%1@%2\n"
	       "Failed to validate ionization rule.")
	   .arg(__FILE__)
	   .arg(__LINE__),
	   QMessageBox::Ok);

	return;
      }

    // Get the pointer to the input list dialog window.

    MzLabInputOligomerTableViewDlg *dlg = 0;
    dlg = mp_mzLabWnd->inputListDlg();
    if (!dlg)
      {
        QMessageBox::warning(this,
                             tr("massXpert: mz Lab"),
                             tr("%1@%2\n"
                                "Please, select one input list first.")
                             .arg(__FILE__)
                             .arg(__LINE__));
	return;
      }
    
    // Is the calculation to be performed inside the input list dialog
    // window, or are we going to create a new mz list with the
    // results of that calculation?
    bool inPlace = mp_mzLabWnd->inPlaceCalculation();

    // Finally actually have the calculation performed by the mz input
    // list dialog window.
    dlg->applyIonizeRule(ionizeRule, inPlace);
  }




} // namespace massXpert
