/* 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
 */


/////////////////////// Qt includes
#include <QObject>
#include <QMainWindow>
#include <QHash>
#include <QMap>
#include <QDebug>
#include <QThread>


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


int massSpecDataFileLoaderSPtrMetaTypeId =
  qRegisterMetaType<MsXpS::MineXpert::MassSpecDataFileLoaderSPtr>(
    "MsXpS::MineXpert::MassSpecDataFileLoaderSPtr");

namespace MsXpS
{
namespace MineXpert
{


//! Construct a MassSpecDataFileLoader instance.
/*!

  \param Name of the file to load.

*/
MassSpecDataFileLoader::MassSpecDataFileLoader(const QString &fileName,
                                               bool load_fully_in_memory,
                                               QObject *parent)
  : MsXpS::libXpertMassCore::MonitoredTaskInterface(parent),
    m_isLoadFullInMemory(load_fully_in_memory)
{
  if(!fileName.isEmpty())
    m_fileName = fileName;
}

//! Destruct \c this MassSpecDataFileLoader instance.
MassSpecDataFileLoader::~MassSpecDataFileLoader()
{
}

//! Set the MsRunDataSet in which to store the mass data.
/*!

  When loading a mass spectrometry data file, the data are stored in various
  structures all belonging to the MsRunDataSet instance passed as
  parameter.

  \param msRunDataSet pointer to a MsRunDataSet instance in which to
  store the mass data loaded from file.

*/
void
MassSpecDataFileLoader::setMsRunDataSet(MsRunDataSetSPtr &ms_run_data_set_sp)
{
  if(ms_run_data_set_sp == nullptr)
    qFatal() << "Programming error.";

  // Let's see the usage count of the MsRunDataSetCstSPtr.
  // qDebug() << "Usage count:" << ms_run_data_set_sp.use_count();

  msp_msRunDataSet = ms_run_data_set_sp;

  // Let's see the usage count of the MsRunDataSetCstSPtr.
  // qDebug() << "Usage count:" << ms_run_data_set_sp.use_count();
}

MsRunDataSetSPtr
MassSpecDataFileLoader::getMsRunDataSet()
{
  return msp_msRunDataSet;
}

//! Set the name of the file to load.
/*!

  \param fileName name of the file.

*/
void
MassSpecDataFileLoader::setFileName(const QString &fileName)
{
  m_fileName = fileName;
}

//! Cancel the running operation.
/*!

  This function can be invoked to ask the loader to stop loading mass data from
  the file.

*/
void
MassSpecDataFileLoader::cancelOperation()
{
  m_isOperationCancelled = true;
}

bool
MassSpecDataFileLoader::shouldStop()
{
  return m_isOperationCancelled;
}

void
MassSpecDataFileLoader::spectrumListHasSize(std::size_t size)
{
  m_spectrumListSize = size;

  emit spectrumListSizeSignal(size);

  qDebug() << "20240529 - The spectrum list has size:" << m_spectrumListSize;
}

// This function is a callback that is called each time a new spectrum is read
// from file. The data reading work is performed by pappso::MsRunReaderSp. Note
// that the qualified mass spectrum might have a mass spectrum pointer that is
// nullptr if the binary data (mz,i) were not asked for.
void
MassSpecDataFileLoader::setQualifiedMassSpectrum(
  const pappso::QualifiedMassSpectrum &qualified_mass_spectrum)
{

  // qDebug() << "from thread:" << QThread::currentThread()
  // << "qualified mass spectrum:" << &qualified_mass_spectrum;

  if(qualified_mass_spectrum.isEmptyMassSpectrum())
    {
      qDebug() << "Spectrum has no binary data, returning.";
      return;
    }

  pappso::QualifiedMassSpectrumCstSPtr qualified_mass_spectrum_csp =
    qualified_mass_spectrum.makeQualifiedMassSpectrumCstSPtr();

  if(qualified_mass_spectrum_csp == nullptr ||
     qualified_mass_spectrum_csp.get() == nullptr)
    qFatal() << "Cannot be nullptr";

  // Note that this is no more true: the pointer can be nullptr if the data are
  // loaded, which is now the default and soon the unique mode, in streamed
  // mode.
  // if(const_cast<pappso::QualifiedMassSpectrum *>(
  // qualified_mass_spectrum_csp.get())
  //->getMassSpectrumSPtr() != nullptr)
  // qFatal() << "Cannot be non-nullptr";

  // qDebug() << "Now mapping new qualified mass spectrum.";
  msp_msRunDataSet->mapMassSpectrum(qualified_mass_spectrum_csp);

  // Increment the count of qualified mass spectra that were added and emit that
  // new count.  And emit a textual representation of the current task
  // situation.

  double retention_time = qualified_mass_spectrum_csp->getRtInMinutes();

  ++m_setQualifiedMassSpectrumCount;

  emit taskSetStatusMessageAndCurrentValueSignal(
    QString("Added %1 spectra over %2 (retention time: %3)")
      .arg(m_setQualifiedMassSpectrumCount)
      .arg(m_spectrumListSize)
      .arg(retention_time, 0, 'f', 1),
    m_setQualifiedMassSpectrumCount);
}

int
MassSpecDataFileLoader::loadDataFromString(const QString &msDataString,
                                           MsRunDataSet *msRunDataSet)
{
  if(msRunDataSet == nullptr)
    qFatal() << "Programming error.";

  QStringList msDataList = msDataString.split("\n");

  if(msDataList.isEmpty())
    return 0;

  pappso::MassSpectrumSPtr mass_spectrum_sp =
    std::make_shared<pappso::MassSpectrum>();

  mass_spectrum_sp->reserve(msDataList.size());

  QRegularExpressionMatch regExpMatch;

  for(int iter = 0; iter < msDataList.size(); ++iter)
    {
      QString line = msDataList.at(iter);

      if(line.startsWith('#') || line.isEmpty() ||
         gEndOfLineRegExp.match(line).hasMatch())
        continue;

      pappso::DataPoint dataPoint;
      if(!dataPoint.initialize(line) || !dataPoint.isValid())
        {
          qDebug() << "Failed to create a data point instance with text:"
                   << line.toLatin1().data() << "Program aborted.";
          return -1;
        }

      mass_spectrum_sp->push_back(dataPoint);
    }

  pappso::QualifiedMassSpectrum qualified_mass_spectrum(mass_spectrum_sp);
  pappso::QualifiedMassSpectrumCstSPtr qualified_mass_spectrum_csp =
    qualified_mass_spectrum.makeQualifiedMassSpectrumCstSPtr();

  // Now that we have crafted the mass spectrum, add it to the mass spec data
  // set.
  msRunDataSet->mapMassSpectrum(qualified_mass_spectrum_csp);

  return msRunDataSet->size();
}

bool
MassSpecDataFileLoader::needPeakList() const
{
  return m_isLoadFullInMemory;
}

void
MassSpecDataFileLoader::loadingEnded()
{
  // qDebug() << "Loading ended !";
}

} // namespace MineXpert
} // namespace MsXpS
