/* BEGIN software license
 *
 * msXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright(C) 2009,...,2019 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 <QMainWindow>
#include <QDir>


/////////////////////// pappsomspp includes
#include <pappsomspp/msfile/msfileaccessor.h>
#include <pappsomspp/massspectrum/qualifiedmassspectrum.h>
#include <pappsomspp/widget/plotwidget/baseplotwidget.h>


/////////////////////// Local includes
#include "config.h"
#include "AboutDlg.hpp"

#include "OpenMsRunDataSetsDlg.hpp"

#include "../nongui/MassDataIntegrator.hpp"
#include "../nongui/MassDataIntegratorTask.hpp"

#include "TaskMonitorWnd.hpp"

#include "DataPlottableTree.hpp"
#include "../nongui/MassSpecDataFileLoader.hpp"

#include "BasePlotCompositeWidget.hpp"

#include "TicXicChromTracePlotWnd.hpp"
#include "MassSpecTracePlotWnd.hpp"
#include "DriftSpecTracePlotWnd.hpp"

#include "DriftSpecMassSpecColorMapWnd.hpp"
#include "TicXicChromMassSpecColorMapWnd.hpp"
#include "TicXicChromDriftSpecColorMapWnd.hpp"

#include "XicExtractionWnd.hpp"

#include "ConsoleWnd.hpp"

#include "MassPeakShaperDlg.hpp"
#include "IsoSpecDlg.hpp"

#include "../nongui/AnalysisPreferences.hpp"
#include "AnalysisPreferencesDlg.hpp"


// All the integrators that are based on the use of Qualified Mass Spectrum
// Vector Visitors.

#include "../nongui/QualifiedMassSpectrumVectorMassDataIntegratorToRt.hpp"
#include "../nongui/QualifiedMassSpectrumVectorMassDataIntegratorToDt.hpp"
#include "../nongui/QualifiedMassSpectrumVectorMassDataIntegratorToMz.hpp"
#include "../nongui/QualifiedMassSpectrumVectorMassDataIntegratorToTicInt.hpp"
#include "../nongui/QualifiedMassSpectrumVectorMassDataIntegratorToDtRtMz.hpp"
#include "../nongui/QualifiedMassSpectrumVectorMassDataIntegratorToRtDt.hpp"


namespace msxps
{
namespace minexpert
{

class MsRunReadTask;

class ProgramWindow : public QMainWindow
{
  Q_OBJECT

  friend class BasePlotWnd;
  friend class BaseTracePlotWnd;

  friend class TicXicChromTracePlotWnd;
  friend class TicXicChromMassSpecColorMapWnd;

  friend class MassSpecTracePlotWnd;

  friend class DriftSpecTracePlotWnd;
  friend class DriftSpecMassSpecColorMapWnd;

  friend class XicExtractionWnd;

  friend class OpenMsRunDataSetsDlg;

  public:
  explicit ProgramWindow(QWidget *parent, const QString &module_name);
  virtual ~ProgramWindow();

  const QString &moduleName() const;

  void setMaxThreadUseCount(std::size_t count);
  std::size_t getMaxThreadUseCount();

  bool openMassSpectrometryFileDlg(const QString &dir_name = QDir::homePath(),
                                   bool full_in_memory     = false);
  bool openMassSpectrometryFile(const QString &fileName    = QString(),
                                bool full_in_memory        = false,
                                const QString &sample_name = QString());
  bool openMassSpectrometryFileFromClipBoard();
  bool openMassSpectrometryFileFromText(const QString &text,
                                        const QString &sample_name);

  void openAnalysisPreferencesDlg();

  void msRunDataSetRemovalRequested(MsRunDataSetCstSPtr &ms_run_data_set_csp);

  const DataPlottableTree &getDataPlottableTree() const;

  std::vector<MsRunDataSetCstSPtr> allSelectedOrUniqueMsRunDataSet();

  BaseTracePlotWnd *getPlotWndPtr(const QString &type_name);
  TaskMonitorWnd *getTaskMonitorWnd() const;

  void seedInitialTicChromatogramAndMsRunDataSetStatistics(
    MsRunDataSetSPtr &ms_run_data_set_sp);

  void integrateToRt(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToMz(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToDt(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToTicIntensity(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToDtMz(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToRtMz(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToRtDt(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  using QualifiedMassSpectraVector =
    std::vector<pappso::QualifiedMassSpectrumCstSPtr>;

  void integrateFromMsRunDataSetTableViewToRt(
    MsRunDataSetCstSPtr ms_run_data_set_csp,
    std::shared_ptr<QualifiedMassSpectraVector>
      vector_of_qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow,
    const QColor &color);

  void integrateFromMsRunDataSetTableViewToDt(
    MsRunDataSetCstSPtr ms_run_data_set_csp,
    std::shared_ptr<QualifiedMassSpectraVector>
      vector_of_qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow,
    const QColor &color);

  void integrateFromMsRunDataSetTableViewToMz(
    MsRunDataSetCstSPtr ms_run_data_set_csp,
    std::shared_ptr<std::vector<pappso::QualifiedMassSpectrumCstSPtr>>
      qualified_mass_spectra_vector_sp,
    const ProcessingFlow &processing_flow,
    const QColor &color);

  void integrateFromMsRunDataSetTableViewToTicIntensity(
    MsRunDataSetCstSPtr ms_run_data_set_csp,
    std::shared_ptr<QualifiedMassSpectraVector>
      vector_of_qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow,
    const QColor &color);

  void integrateFromMsRunDataSetTableViewToDtRtMz(
    pappso::DataKind data_kind,
    MsRunDataSetCstSPtr ms_run_data_set_csp,
    std::shared_ptr<QualifiedMassSpectraVector>
      vector_of_qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow,
    const QColor &color);

  void integrateFromMsRunDataSetTableViewToRtDt(
    pappso::DataKind data_kind,
    MsRunDataSetCstSPtr ms_run_data_set_csp,
    std::shared_ptr<QualifiedMassSpectraVector>
      vector_of_qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow,
    const QColor &color);

  void xicIntegrationToRt(const ProcessingFlow &processing_flow);

  void displayMassSpectralTrace(pappso::Trace trace,
                                const ProcessingFlow &processing_flow,
                                const QString &sample_name);

  const BasePlotCompositeWidget *
  getPlotWidget(MsRunDataSetCstSPtr ms_run_data_set_csp,
                QCPAbstractPlottable *plottable_p);

  void
  documentMsRunDataPlottableFiliation(MsRunDataSetCstSPtr ms_run_data_set_csp,
                                      QCPAbstractPlottable *new_plottable_p,
                                      QCPAbstractPlottable *parent_plottable_p,
                                      BasePlotCompositeWidget *plot_widget_p);

  void plottableDestructionRequested(
    BasePlotCompositeWidget *base_plot_composite_widget_p,
    QCPAbstractPlottable *plottable_p,
    const pappso::BasePlotContext &context);

  void plottableDestructionRequested(
    BasePlotCompositeWidget *base_plot_composite_widget_p,
    QCPAbstractPlottable *plottable_p,
    bool recursively = false);

  void plotCompositeWidgetDestructionRequested(
    BasePlotCompositeWidget *base_plot_composite_widget_p);

  public slots:

  void finishedReadingMsRunData(MsRunDataSetSPtr ms_run_data_set_sp);

  void finishedSeedingInitialTicChromatogramAndMsRunDataSetStatistics(
    MassDataIntegrator *mass_data_integrator_p);

  void finishedXicIntegrationToRt(MassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToRt(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToDt(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToMz(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToTicIntensity(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToDtRtMz(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToRtDt(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void logTextToConsole(QString msg);
  void logColoredTextToConsole(QString text, const QColor &color);

  QColor getColorForMsRunDataSet(MsRunDataSetCstSPtr ms_run_data_set_csp) const;

  signals:

  void readMsRunDataSignal(MsRunReadTask *ms_run_read_task_p,
                           pappso::MsRunReaderSPtr ms_run_reader_sp,
                           std::shared_ptr<MassSpecDataFileLoader> loader_sp);

  void seedInitialTicChromatogramAndMsRunDataSetStatisticsSignal(
    MsRunDataSetTreeMassDataIntegratorToRt *mass_data_integrator_p);

  void integrateToRtSignal(
    MsRunDataSetTreeMassDataIntegratorToRt *mass_data_integrator_p);

  void integrateQualifiedMassSpectrumVectorToRtSignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToRt *mass_data_integrator_p);

  void integrateQualifiedMassSpectrumVectorToDtSignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToDt *mass_data_integrator_p);

  void integrateQualifiedMassSpectrumVectorToMzSignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToMz *mass_data_integrator_p);

  void integrateQualifiedMassSpectrumVectorToTicIntensitySignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToTicInt
      *mass_data_integrator_p);

  void integrateQualifiedMassSpectrumVectorToRtDtSignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToRtDt *mass_data_integrator_p,
    pappso::DataKind data_kind);

  void integrateQualifiedMassSpectrumVectorToDtRtMzSignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToDtRtMz
      *mass_data_integrator_p,
    pappso::DataKind data_kind);

  void ticIntensityValueSignal(double tic_intensity);

  void cancelOperationSignal();

  protected:
  //! The name of the module, at the moment massXpert or mineXpert.
  QString m_moduleName = "mineXpert2";

  std::size_t m_loadedFileCount = 0;
  QString m_msRunIdPrefix       = "file-";
  QString m_lastUsedDirectory   = QDir::homePath();

  int m_selectedMsRunIndex = -1;

  // The user can limit the max number of threads to use. 0 is no limitation
  // (all the available threads are going to be used).
  std::size_t m_maxThreadUseCount = 0;

  // We need to track all the plot widgets and plottables. This tree aims at
  // storing the structure of all the plottables in all the plot widgets, in all
  // the windows, for all the ms run data sets.

  DataPlottableTree m_dataPlottableTree;

  /****************************************************************/
  /* All the windows (dlg or not) */
  /****************************************************************/

  OpenMsRunDataSetsDlg *mp_openMsRunDataSetsDlg = nullptr;

  TicXicChromTracePlotWnd *mp_ticXicChromPlotWnd = nullptr;
  MassSpecTracePlotWnd *mp_massSpecPlotWnd       = nullptr;
  DriftSpecTracePlotWnd *mp_driftSpecPlotWnd     = nullptr;

  DriftSpecMassSpecColorMapWnd *mp_driftSpecMassSpecColorMapWnd       = nullptr;
  TicXicChromMassSpecColorMapWnd *mp_ticXicChromMassSpecColorMapWnd   = nullptr;
  TicXicChromDriftSpecColorMapWnd *mp_ticXicChromDriftSpecColorMapWnd = nullptr;

  XicExtractionWnd *mp_xicExtractionWnd = nullptr;

  TaskMonitorWnd *mp_taskMonitorWnd = nullptr;

  ConsoleWnd *mp_consoleWnd = nullptr;

  MassPeakShaperDlg *mp_massPeakShaperDlg = nullptr;

  IsoSpecDlg *mp_isoSpecDlg = nullptr;

  AnalysisPreferences *mpa_analysisPreferences = nullptr;
  AnalysisPreferences *getAnalysisPreferences();

  AnalysisPreferencesDlg *mp_analysisPreferencesDlg = nullptr;

  QFile *mpa_analysisFile = nullptr;
  QFile *getAnalysisFilePtr();

  void recordAnalysisStanza(QString stanza, const QColor &color = Qt::black);

  AboutDlg *mp_aboutDlg = nullptr;

  // The map that relates each MS run data set with the corresponding ms run
  // data set table view window.
  std::map<MsRunDataSetCstSPtr, MsRunDataSetTableViewWnd *>
    mp_msRunDataSetTableViewWndMap;

  QMenu *mp_fileMenu                = nullptr;
  QMenu *mp_windowsMenu             = nullptr;
  QMenu *mp_utilitiesMenu           = nullptr;
  QMenu *mp_preferencesMenu           = nullptr;
  QMenu *mp_helpMenu                = nullptr;
  QAction *mp_openFullMsFileAct     = nullptr;
  QAction *mp_openStreamedMsFileAct = nullptr;
  QAction *mp_quitAct;

  void writeSettings();
  void readSettings();

  void initializeAllWindows();
  void createMenusAndActions();

  void setupWindow();

  int selectMsRun(std::vector<pappso::MsRunIdCstSPtr> &ms_run_ids);

  /****************************************************************/
  /* All the windows (dlg or not) */
  /****************************************************************/

  AboutDlg *showAboutDlg();

  void showOpenMsRunDataSetsWnd();
  const OpenMsRunDataSetsDlg *getOpenMsRunDataSetsDlg() const;

  void showTicXicChromatogramsWnd();
  void showMassSpectraWnd();
  void showDriftSpectraWnd();

  void showXicExtractionWnd();

  void showTicXicChromMassSpecColorMapWnd();
  void showTicXicChromDriftSpecColorMapWnd();
  void showDriftSpecMassSpecColorMapWnd();

  void showTaskMonitorWnd();

  void showConsoleWnd();

  void saveWorkspace();

  void showMsRunDataSetTableViewWnd(MsRunDataSetCstSPtr ms_run_data_set_csp,
                                    const QColor &color);

  void showMassPeakShaperDlg();
  void showIsoSpecDlg();

  void cancelOperationPushButtonClicked();

  void closeEvent(QCloseEvent *event);

  void calculateInitialMsRunDataSetStatistics(
    MsRunDataSetCstSPtr ms_run_data_set_csp);
};


} // namespace minexpert

} // namespace msxps
