/* 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 <QObject>
#include <QDir>


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


/////////////////////// libXpertMassCore includes
#include <MsXpS/libXpertMassCore/MassDataServer.hpp>
#include <MsXpS/libXpertMassCore/MassDataClient.hpp>
#include <MsXpS/libXpertMassCore/RecentFilesHandler.hpp>


/////////////////////// libXpertMassGui includes
#include <MsXpS/libXpertMassGui/MassDataClientServerConfigDlg.hpp>
#include <MsXpS/libXpertMassGui/IsotopicClusterGeneratorDlg.hpp>
#include <MsXpS/libXpertMassGui/IsotopicClusterShaperDlg.hpp>
#include <MsXpS/libXpertMassGui/JavaScriptingEnvironment.hpp>
#include <MsXpS/libXpertMassGui/JavaScriptingGuiUtils.hpp>
#include <MsXpS/libXpertMassGui/JavaScriptingWnd.hpp>
#include <MsXpS/libXpertMassGui/ActionManager.hpp>
#include <MsXpS/libXpertMassGui/TaskMonitorWnd.hpp>


/////////////////////// Local includes

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

#include "AboutDlg.hpp"
#include "BasePlotCompositeWidget.hpp"
#include "DataPlottableTree.hpp"
#include "DriftSpecMassSpecColorMapWnd.hpp"
#include "OpenMsRunDataSetsDlg.hpp"
#include "QualifiedMassSpectrumVectorMassDataIntegratorToDt.hpp"
#include "QualifiedMassSpectrumVectorMassDataIntegratorToMz.hpp"
// #include "TaskMonitorWnd.hpp"
#include "TicXicChromDriftSpecColorMapWnd.hpp"
#include "TicXicChromMassSpecColorMapWnd.hpp"
#include "TicXicChromTracePlotWnd.hpp"
#include "XicExtractionWnd.hpp"
#include "MassSpecTracePlotWnd.hpp"
#include "DriftSpecTracePlotWnd.hpp"
#include "ConsoleWnd.hpp"

namespace MsXpS
{
namespace MineXpert
{

class MsRunReadTask;
class MsRunProbeTask;
class ApplicationPreferencesWnd;

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;

  friend class MsRunLoader;
  friend class BrukerTimsTofMsRunLoader;
  friend class PwizLiteMsRunLoader;

  ////////////////////////////// public //////////////////////////// /
  ////////////////////////////// public //////////////////////////////

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

  const QString &applicationName() const;

  void setMaxThreadUseCount(int count);
  int getMaxThreadUseCount();

  void incrementLoadedFileCount();

  void setupWindow();

  Q_INVOKABLE bool
  openMassSpectrometryFileDlg(const QString &dir_name = QDir::homePath(),
                              bool full_in_memory     = false);

  Q_INVOKABLE void
  openMassSpectrometryFile(const QString &fileName    = QString(),
                           bool full_in_memory        = false,
                           const QString &sample_name = QString());

  bool readMsRunData(pappso::MsFileAccessorSPtr ms_file_accessor_sp,
                     pappso::MsRunReadConfig ms_run_read_config,
                     bool full_in_memory);

  void openMassSpectrometryFileFromClipBoard();

  void openMassSpectrometryFileFromText(const QString &text,
                                        const QString &sample_name);

  void updateDiscoveriesPreferences(const DiscoveriesPreferences &discovery_preferences);

  void msRunDataSetRemovalRequested(MsRunDataSetCstSPtr &ms_run_data_set_csp);

  const DataPlottableTree &getDataPlottableTree() const;

  std::vector<MsRunDataSetCstSPtr> allSelectedOrUniqueMsRunDataSet();

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

  AboutDlg *showAboutDlg();

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

  void showTicXicChromatogramsWnd();
  void showMassSpectraWnd();
  void showIonMobilitySpectraWnd();

  void showXicExtractionsWnd();

  void showTicXicChromMassSpecColorMapsWnd();
  void showTicXicChromIonMobSpecColorMapsWnd();
  void showIonMobSpecMassSpecColorMapsWnd();

  void showTaskMonitorWnd();

  void showConsoleWnd();

  void showScriptingWnd();
  libXpertMassGui::JavaScriptingWnd *getScriptingWnd();

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

  Q_INVOKABLE void showIsotopicClusterGeneratorDlg();
  void showIsotopicClusterShaperDlg();

  void showApplicationPreferencesWnd();
  const ApplicationPreferencesWnd *getApplicationPreferencesWnd();

  void saveWorkspace();

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

  void seedInitialTicChromatogramAndMsRunDataSetStatistics(
    MsRunDataSetSPtr &ms_run_data_set_sp);

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

  // To trace integrations
  void integrateToDt(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<QualifiedMassSpectraVector> qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

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

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

  // To TIC intensity integration
  void integrateToTicIntensity(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<QualifiedMassSpectraVector> qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  // To color map integrations
  void integrateToDtMz(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<QualifiedMassSpectraVector> qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToDtRt(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<QualifiedMassSpectraVector> qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  void integrateToMzRt(
    QCPAbstractPlottable *parent_plottable_p,
    std::shared_ptr<QualifiedMassSpectraVector> qualified_mass_spectra_sp,
    const ProcessingFlow &processing_flow);

  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);

  bool startClient(const QString &ip_address, int port_number);

  libXpertMassGui::ActionManager *getActionManager();

  ///////////////////////////// public slots /////////////////////////////
  ///////////////////////////// public slots /////////////////////////////

  public slots:

  void finishedSeedingInitialTicChromatogramAndMsRunDataSetStatistics(
    MassDataIntegrator *mass_data_integrator_p);

  void finishedIntegratingQualifiedMassSpectrumVectorToTicIntensity(
    QualifiedMassSpectrumVectorMassDataIntegrator *mass_data_integrator_p);

  void finishedXicIntegrationToRt(MassDataIntegrator *mass_data_integrator_p);

  libXpertMassGui::MassDataClientServerConfigDlg *
  configureNetworkConnection(bool no_dlg_show = false);

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

  QColor getColorForMsRunDataSet(MsRunDataSetCstSPtr ms_run_data_set_csp) const;

  QFile *getAnalysisFilePtr();
  QSharedPointer<DiscoveriesPreferences> getDiscoveriesPreferences();

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

  ///////////////////////////// signals /////////////////////////////
  ///////////////////////////// signals /////////////////////////////

  signals:

  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);

  void integrateQualifiedMassSpectrumVectorToDtRtMzSignal(
    QualifiedMassSpectrumVectorMassDataIntegratorToDtRtMz
      *mass_data_integrator_p);

  void ticIntensityValueSignal(double tic_intensity);

  void cancelOperationSignal();

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

  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).
  int 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;

  libXpertMassGui::JavaScriptingWnd *mp_scriptingWnd = nullptr;
  ApplicationPreferencesWnd *mp_applicationPreferencesWnd = nullptr;

  libXpertMassGui::IsotopicClusterGeneratorDlg *mp_isotopicClusterGeneratorDlg =
    nullptr;
  libXpertMassGui::IsotopicClusterShaperDlg *mp_isotopicClusterShaperDlg =
    nullptr;

  libXpertMassGui::MassDataClientServerConfigDlg *mp_clientServerConfigDlg =
    nullptr;

  QFile *mpa_analysisFile = nullptr;

  AboutDlg *mp_aboutDlg = nullptr;

  QSharedPointer<DiscoveriesPreferences> mqsp_discoveriesPreferences = nullptr;
  // DiscoveriesPreferences *mpa_discoveriesPreferences = nullptr;0

  libXpertMassCore::MassDataClient *mp_massDataClient = nullptr;
  libXpertMassCore::MassDataServer *mp_massDataServer = nullptr;

  libXpertMassGui::ActionManager *mp_actionManager = nullptr;

  libXpertMassGui::TaskMonitorWnd *mp_taskMonitorWnd = 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_recentFilesMenu            = nullptr;
  QAction *mp_recentFilesMenuSeparator = nullptr;

  QMenu *mp_windowsMenu             = nullptr;
  QMenu *mp_utilitiesMenu           = nullptr;
  QMenu *mp_pluginsMenu             = nullptr;
  QMenu *mp_preferencesMenu         = nullptr;
  QMenu *mp_helpMenu                = nullptr;
  QAction *mp_openFullMsFileAct     = nullptr;
  QAction *mp_openStreamedMsFileAct = nullptr;
  QAction *mp_isotopicClusterGeneratorDlgAct;
  QAction *mp_isotopicClusterShaperDlgAct;
  QAction *mp_clientServerConfigDlgAct;
  QAction *mp_quitAct;

  libXpertMassCore::RecentFilesHandler m_recentFilesHandler;

  void writeSettings();
  void readSettings();

  void initializeAllWindows();
  void createMenusAndActions();
  void updateRecentFilesMenu();

  void initializeApplicationPreferencesWnd();

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

  void cancelOperationPushButtonClicked();

  void closeEvent(QCloseEvent *event);

  void calculateInitialMsRunDataSetStatistics(
    MsRunDataSetCstSPtr ms_run_data_set_csp);

  void initializeScripting();
  int loadPlugins(const QString &dir_path);
  int loadPlugins();

  void displayArticleCitationHelpPage();

  bool startServer();
  void stopServer();
  void stopClient();

  void dispatchReceivedData(const QByteArray &byte_array);

  private slots:

  void massDataToBeServed(const QByteArray &byte_array);
};


} // namespace MineXpert

} // namespace MsXpS
