/**
 * \file /output/mcqr/mcqrdata.h
 * \date 05/01/2021
 * \author Thomas Renne
 * \brief write Rdata used by MCQR
 */

/*******************************************************************************
 * Copyright (c) 2021 Thomas Renne <thomas.renne@e.email>.
 *
 * This file is part of XTPcpp.
 *
 *     XTPcpp 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.
 *
 *     XTPcpp 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 XTPcpp.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contributors:
 *     Thomas Renne <thomas.renne@e.email> - initial API and
 *implementation
 ******************************************************************************/

#pragma once

#include <sys/types.h>
#include <QString>
#include "../../core/project.h"
#include <pappsomspp/processing/uimonitor/uimonitorinterface.h>

extern "C"
{
#include <rdata.h>
}

class McqrRdata
{
  public:
  McqrRdata(McqrExperimentSp mcqr_experiment_sp, ProjectSp project);
  ~McqrRdata();


  void writeSpectralCountData(pappso::UiMonitorInterface &monitor);


  private:
  static ssize_t write_data(const void *bytes, size_t len, void *ctx);
  std::size_t getNumberOfRow(bool is_spectral_count);
  std::size_t getExperimentalSummaryRowNumber();
  std::vector<rdata_column_t *> createMetadataColumns();


  // Create the Tables
  void writeMetaDataTable(const QFileInfo &meta_datafile);
  void writeSpectraCountTable(const QFileInfo &sctable_datafile);
  void writeQuantiInfoTable(const QFileInfo &quanti_info_datafile);
  void
  writeExperimentalSummaryTable(const QFileInfo &experimental_summary_datafile);

  // Close the RData File
  void closeMCQRDataFile();

  /** @brief Merge the created RData files into a unique RData file and delete
   * the others
   */
  static void mergeTheRDataFiles(const QString script_path);

  /** @brief Create the merging data rscript based on the template and save it
   * at the given location.
   * @param QString file path where the Rscript will be written
   * @param QString file path of the RData parts.
   */
  static QString createTheMergeRScript(const QString tmp_path,
                                       const QString final_rdata_path,
                                       const QString masschroqml_path);

  private:
  ProjectSp msp_project;
  McqrExperimentSp msp_mcqrExperiment;
  QString m_rdataFilePath;
  rdata_writer_t *mp_rdataWriter;
  int m_rdataFile;
};
