/**
 * \file core/tandem_run/tandemslurmprocess.h
 * \date 21/09/2023
 * \author Olivier Langella
 * \brief handles execution of a bunch of X!Tandem process through slurm
 * workload manager
 */

/*******************************************************************************
 * Copyright (c) 2023 Olivier Langella
 *<Olivier.Langella@universite-paris-saclay.fr>.
 *
 * This file is part of i2MassChroQ.
 *
 *     i2MassChroQ 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.
 *
 *     i2MassChroQ 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 i2MassChroQ.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#pragma once

#include "tandembatchprocess.h"
#include <QTemporaryDir>
#include "../../utils/workmonitor.h"
#include "../slurm_process/slurmprocess.h"

/**
 * @todo write docs
 */
class TandemSlurmProcess : public TandemBatchProcess
{
  public:
  TandemSlurmProcess(MainWindow *p_main_window,
                     WorkMonitor *p_monitor,
                     const TandemRunBatch &tandem_run_batch);
  virtual ~TandemSlurmProcess();

  virtual void prepareXmlDatabaseFile();
  virtual void run();

  private:
  struct ProcessUnit
  {
    SlurmProcess *mp_slurmProcess = nullptr;
    QString m_mzInputFile;
    QString m_inputTandemFile;
    bool done = false;
  };


  private:
  QString getSlurmBatchContent(const TandemRunBatch &tandem_run_batch,
                               const QString &input_tandem_file) const;

  void prepareTemporaryDirectory();


  const QTemporaryDir *getTmpDir() const;
  void startProcessUnit(const QString &mz_input_file,
                        const QString &input_tandem_file);

  bool batchIsRunning();
  void killJobs();
  QString whatAboutMyJobs();

  std::size_t countSlurmJobState(SlurmJobState slurm_state) const;


  private:
  std::vector<ProcessUnit> m_processUnitList;
  WorkMonitor *mp_workMonitor               = nullptr;
  uint m_condorRequestMemory                = 5000;
  std::size_t m_slurmStatusTimerMillisecond = 1000;
  QTemporaryDir *mp_tmpDir                  = nullptr;
  QJsonDocument m_jsonSlurmJobStatusDocument;
  std::size_t m_memoryMax    = 0;
  std::size_t m_countJobDone = 0;
};
