
/* BEGIN software license
 *
 * msXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright (C) 2009--2020 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
 */


#pragma once

/////////////////////// StdLib includes


/////////////////////// Qt includes
#include <QWidget>
#include <QFuture>
#include <QList>
#include <QPointer>
#include <QThread>


/////////////////////// QCustomPlot


/////////////////////// pappsomspp includes
#include <pappsomspp/core/trace/datapoint.h>
#include <pappsomspp/gui/plotwidget/massspectraceplotwidget.h>


/////////////////////// libXpertMassCore
#include <MsXpS/libXpertMassCore/AbstractLowMassDeconvolver.hpp>
#include <MsXpS/libXpertMassCore/LowMassDeconvolverWorker.hpp>
#include <MsXpS/libXpertMassCore/DeconvolutedMassIdMatcher.hpp>
#include <MsXpS/libXpertMassCore/MassSpectrumSynthesizer.hpp>


/////////////////////// Local includes
#include "BaseTracePlotCompositeWidget.hpp"

namespace MsXpS
{
namespace MineXpert
{

class LowMassDeconvolverWorker;

// class QThread;

class MassSpecTracePlotCompositeWidget: public BaseTracePlotCompositeWidget
{
  Q_OBJECT

  public:
  struct UserData
  {
    void *initialSourcePlottable = nullptr;
    bool shouldIdentify          = false;
    QString labelFontString;
    QString labelListName;
    bool shouldWriteLabels;
    bool shouldAddLabelToList;
  };

  explicit MassSpecTracePlotCompositeWidget(QWidget *parent,
                                            const QString &x_axis_label,
                                            const QString &y_axis_label);
  virtual ~MassSpecTracePlotCompositeWidget();

  using BaseTracePlotCompositeWidget::plotWidgetKeyPressEvent;

  public slots:

  void
  plotWidgetMassDeconvolution(const pappso::MassSpecTracePlotContext &context);

  void plotWidgetResolvingPowerComputation(
    const pappso::MassSpecTracePlotContext &context);

  virtual void lastCursorHoveredPoint(const QPointF &pointf) override;

  virtual void
  plotWidgetKeyPressEvent(const pappso::MassSpecTracePlotContext &context);

  virtual void
  plotWidgetKeyReleaseEvent(const pappso::BasePlotContext &context)override;

  virtual void
  plotWidgetMousePressEvent(QMouseEvent *event,
                            const pappso::MassSpecTracePlotContext &context);

  virtual void
  plotWidgetMouseReleaseEvent(QMouseEvent *event,
                              const pappso::MassSpecTracePlotContext &context);

  virtual void moveMouseCursorToNextGraphPoint(
    const pappso::BasePlotContext &context) override;

  void integrationRequested(const pappso::BasePlotContext &context);

  void gaussianFitOnVisibleMaxima();

  std::tuple<QCPBars *, pappso::Trace> extractAndDisplayCentroids();

  QList<libXpertMassCore::DeconvolutedFeature> lowMassDeconvolve();

  pappso::Trace synthesizeMassSpectrumOld(
    QList<libXpertMassCore::DeconvolutedFeature> &deconvoluted_features,
    QCPAbstractPlottable *source_plottable_p);

  void synthesizeMassSpectrum(
    QList<libXpertMassCore::DeconvolutedFeature> &deconvoluted_features,
    QCPAbstractPlottable *source_plottable_p,
    const QString &sample_name,
    const QString &sample_color_name,
    const QString &mass_pectrum_title,
    bool should_identify);

  void identifyAnalytes(
    QList<libXpertMassCore::DeconvolutedFeature> &deconvoluted_features,
    QCPAbstractPlottable *source_plottable_p);


  virtual QCPGraph *addTrace(const pappso::Trace &trace,
                             QCPAbstractPlottable *parent_plottable_p,
                             MsRunDataSetCstSPtr ms_run_data_set_csp,
                             const QString &sample_name,
                             const ProcessingFlow &processing_flow,
                             const QColor &color) override;

  virtual QCPBars *addBars(const pappso::Trace &trace,
                             QCPAbstractPlottable *parent_plottable_p,
                             MsRunDataSetCstSPtr ms_run_data_set_csp,
                             const QString &sample_name,
                             const ProcessingFlow &processing_flow,
                             const QColor &color);

  void setMinimalChargeFractionalPartPinnedDownWidgets(double value);
  void setChargeStateEnvelopePeakSpanPinnedDownWidgets(std::size_t value);

  void
  peakPickDeconvOnlyForVisibleRangeCheckBoxStateChanged(Qt::CheckState state);

  private slots:

  void onDeconvolutionFinished(
    QList<libXpertMassCore::DeconvolutedFeature> deconvoluted_features,
    void *centroids_source_plottable_p,
    const QString &sample_name,
    const QString &sample_color_name,
    bool should_synthesize,
    const QString &mass_spectrum_title,
    bool should_identify);
  void onDeconvolutionError(const QString &message);
  void onDeconvolutionProgress(int percent);
  void onDeconvolutionStatus(const QString &message);

  void onMassSpectrumSynthesizerFinished(pappso::Trace synthetic_mass_spectrum,
                                         QString mass_spectum_title,
                                         QString mass_spectrum_color,
                                         void *user_data_vp);

  void onMassSpectrumSynthesizerTaskErrorSignal(
    MsXpS::libXpertMassCore::ErrorList *error_list_p);

  void onAnalyteIdentificationFinished(void *initial_source_plottable,
                                       const QString &sample_name,
                                       const QString &label_color_string,
                                       const QString &label_font_string,
                                       const QString &label_list_name,
                                       bool should_write_labels,
                                       bool should_add_label_to_list);

  signals:

  protected:
  bool m_isPeakPickDeconvOnlyForVisibleRange = false;
  QList<libXpertMassCore::DeconvolutedFeature> m_deconvolutedFeatures;
  virtual void createMainMenu() override;

  QString craftAnalysisStanza(const pappso::MassSpecTracePlotContext &context);

  private:
  QAction *mrp_lowMassDeconvolveAction = nullptr;
  QPointer<QThread> mqp_deconvolutionThread;
  QPointer<libXpertMassCore::LowMassDeconvolverWorker> mqp_deconvolutionWorker;

  QPointer<QThread> mqp_analyteIdentificationThread;
  QPointer<libXpertMassCore::DeconvolutedMassIdMatcher>
    mqp_deconvolutedMassIdMatcher;

  pappso::Trace m_syntheticMassSpectrum;

  bool m_spectrumSynthesisInProgress = false;

  // For the mass spectra that are synthesized and served.
  QString m_colorName;
  QPointer<QThread> mqp_spectrumSynthesizerThread;
  QPointer<libXpertMassCore::MassSpectrumSynthesizer>
    mqp_massSpectrumSynthesizer;

  // Store these for potential cancellation
  bool m_deconvolutionInProgress = false;
  bool m_analyteIdentificationInProgress = false;
  virtual void setupWidget() override;
};


} // namespace MineXpert
} // namespace MsXpS
