/* 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 <QObject>
#include <QDebug>
#include <QWidget>
#include <QMessageBox>
#include <QSettings>
#include <QLineEdit>


/////////////////////// Local includes
#include <globals/globals.hpp>
#include <minexpert/gui/XicExtractionWnd.hpp>
#include <minexpert/gui/OpenSpectraDlg.hpp>
#include <minexpert/gui/MainWindow.hpp>


namespace msXpSmineXpert
{

XicExtractionWnd::XicExtractionWnd(QWidget *parent) : QMainWindow{parent}
{
  // qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "()";

  if(parent == Q_NULLPTR)
    qFatal(
      "Fatal error at %s@%d -- %s(). "
      "Pointer to the parent window cannot be nullptr."
      "Program aborted.",
      __FILE__,
      __LINE__,
      __FUNCTION__);

  m_ui.setupUi(this);

  initialize();
}


XicExtractionWnd::~XicExtractionWnd()
{
  writeSettings();
}


void
XicExtractionWnd::readSettings()
{
  QSettings settings;
  settings.beginGroup("XicExtractionWnd");

  // Remember the last tolerance value and type.
  double tolerance = 0.01;

  QVariant variant = settings.value("tolerance");
  if(variant.isValid())
    tolerance = variant.toDouble();

  m_ui.toleranceLineEdit->setText(QString("%1").arg(tolerance, 0, 'f', 3));

  int type = msXpS::MassToleranceType::MASS_TOLERANCE_PPM;
  variant  = settings.value("type");
  if(variant.isValid())
    type = variant.toInt();

  m_ui.toleranceTypeComboBox->setCurrentText(
    msXpS::massToleranceTypeMap.value(type));

  // Also restore the geometry of the window.
  restoreGeometry(settings.value("geometry").toByteArray());

  bool wasVisible = settings.value("visible").toBool();
  setVisible(wasVisible);

  settings.endGroup();
}


void
XicExtractionWnd::writeSettings()
{
  QSettings settings;
  settings.beginGroup("XicExtractionWnd");

  settings.setValue("tolerance", m_ui.toleranceLineEdit->text());
  settings.setValue(
    "type",
    msXpS::massToleranceTypeMap.key(m_ui.toleranceTypeComboBox->currentText()));

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

  settings.setValue("visible", isVisible());

  settings.endGroup();
}


QString
XicExtractionWnd::availableToleranceTypes()
{
  QString text;

  for(int iter = msXpS::MassToleranceType::MASS_TOLERANCE_NONE;
      iter < msXpS::MassToleranceType::MASS_TOLERANCE_LAST;
      ++iter)
    {
      text.append(msXpS::massToleranceTypeMap.value(iter));
      text.append("\n");
    }

  return text;
}


void
XicExtractionWnd::initialize()
{
  QStringList typeList;

  for(int iter = msXpS::MassToleranceType::MASS_TOLERANCE_NONE;
      iter < msXpS::MassToleranceType::MASS_TOLERANCE_LAST;
      ++iter)
    {
      typeList.append(msXpS::massToleranceTypeMap.value(iter));
    }

  m_ui.toleranceTypeComboBox->insertItems(0, typeList);

  readSettings();

  connect(m_ui.applyPushButton,
          &QPushButton::clicked,
          this,
          &XicExtractionWnd::apply);
  connect(m_ui.abortPushButton,
          &QPushButton::clicked,
          this,
          &XicExtractionWnd::abort);
  connect(m_ui.closePushButton,
          &QPushButton::clicked,
          this,
          &XicExtractionWnd::close);
}


bool
XicExtractionWnd::setMz(double value)
{
  m_ui.mzLineEdit->setText(QString("%1").arg(value, 0, 'f', 6));
  return true;
}


bool
XicExtractionWnd::setTolerance(double value)
{
  m_ui.toleranceLineEdit->setText(QString("%1").arg(value, 0, 'f', 6));
  return true;
}


bool
XicExtractionWnd::setToleranceType(int value)
{
  QString text = msXpS::massToleranceTypeMap.value(value, "error");
  if(text == "error")
    return false;

  m_ui.toleranceTypeComboBox->setCurrentText(text);
  return true;
}


bool
XicExtractionWnd::setToleranceType(QString text)
{
  int value = msXpS::massToleranceTypeMap.key(text, -1);
  if(value == -1)
    return false;

  m_ui.toleranceTypeComboBox->setCurrentText(text);
  return true;
}


bool
XicExtractionWnd::apply()
{
  bool ok   = false;
  double mz = m_ui.mzLineEdit->text().toDouble(&ok);
  if(!ok)
    {
      qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "()"
               << "Please enter a valid m/z double value";

      return false;
    }

  double tolerance = m_ui.toleranceLineEdit->text().toDouble(&ok);
  if(!ok)
    {
      qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "()"
               << "Please enter a valid tolerance double value";

      return false;
    }

  QString toleranceTypeString = m_ui.toleranceTypeComboBox->currentText();

  int toleranceType = msXpS::massToleranceTypeMap.key(toleranceTypeString);

  double mzStart;
  double mzEnd;

  if(toleranceType == msXpS::MassToleranceType::MASS_TOLERANCE_NONE)
    {
      mzStart = mz;
      mzEnd   = mz;
    }
  else if(toleranceType == msXpS::MassToleranceType::MASS_TOLERANCE_AMU)
    {
      mzStart = mz - (tolerance / 2);
      mzEnd   = mz + (tolerance / 2);
    }
  else if(toleranceType == msXpS::MassToleranceType::MASS_TOLERANCE_MZ)
    {
      mzStart = mz - (tolerance / 2);
      mzEnd   = mz + (tolerance / 2);
    }
  else if(toleranceType == msXpS::MassToleranceType::MASS_TOLERANCE_RES)
    {
      double mzTemp = msXpS::addRes(mz, tolerance);

      mzStart = mz - (mzTemp / 2);
      mzEnd   = mz + (mzTemp / 2);
    }
  else if(toleranceType == msXpS::MassToleranceType::MASS_TOLERANCE_PPM)
    {
      double mzTemp = msXpS::addPpm(mz, tolerance);

      mzStart = mz - (mzTemp / 2);
      mzEnd   = mz + (mzTemp / 2);
    }
  else
    qFatal(
      "Fatal error at %s@%d -- %s(). "
      "Programming error."
      "Program aborted.",
      __FILE__,
      __LINE__,
      __FUNCTION__);

  // At this point, get the list of all the mass data files that have their
  // item selected in the OpenSpectraDlg window.
  const OpenSpectraDlg *dlg =
    static_cast<MainWindow *>(parent())->openSpectraDlg();

  QList<AbstractPlotWidget *> plotWidgetList = dlg->selectedPlotWidgets();

  if(!plotWidgetList.size())
    {
      statusBar()->showMessage(
        "No mass data file is selected. Please, select at least one.", 3000);
      return false;
    }

  // At this point, the settings were correct, make sure we cant store
  // them before even starting the work. We'll have them ready even if
  // something bad occurs later.

  writeSettings();

  for(int iter = 0; iter < plotWidgetList.size(); ++iter)
    {
      TicChromPlotWidget *plotWidget =
        static_cast<TicChromPlotWidget *>(plotWidgetList.at(iter));

      qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "()"
               << "IntegrateToXic with mzStart/mzEnd: " << mzStart << "/"
               << mzEnd;

      plotWidget->integrateToXic(mzStart, mzEnd);
    }

  return true;
}


void
XicExtractionWnd::close()
{
  QMainWindow::close();
}


void
XicExtractionWnd::abort()
{
  qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "()"
           << "emit cancelOperationSignal();";
  emit cancelOperationSignal();
}


} // namespace msXpSmineXpert
