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


/////////////////////// StdLib includes


/////////////////////// Qt includes
#include <QDebug>


/////////////////////// pappsomspp includes


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


namespace msxps
{
namespace minexpert
{


BaseMsRunDataSetTreeNodeVisitor::BaseMsRunDataSetTreeNodeVisitor(
  MsRunDataSetCstSPtr ms_run_data_set_csp,
  const ProcessingFlow &processing_flow)
  : mcsp_msRunDataSet(ms_run_data_set_csp), m_processingFlow(processing_flow)
{
  //  qDebug() << "Processing flow has" << m_processingFlow.size() << "steps";
}


BaseMsRunDataSetTreeNodeVisitor::BaseMsRunDataSetTreeNodeVisitor(
  const BaseMsRunDataSetTreeNodeVisitor &other)
  : QObject(),
    mcsp_msRunDataSet(other.mcsp_msRunDataSet),
    m_processingFlow(other.m_processingFlow),
    m_limitMzRangeStart(other.m_limitMzRangeStart),
    m_limitMzRangeEnd(other.m_limitMzRangeEnd)
{
}


BaseMsRunDataSetTreeNodeVisitor::~BaseMsRunDataSetTreeNodeVisitor()
{
}


void
BaseMsRunDataSetTreeNodeVisitor::setProcessingFlow(
  const ProcessingFlow &processing_flow)
{
  m_processingFlow = processing_flow;
}


void
BaseMsRunDataSetTreeNodeVisitor::setLimitMzRangeStart(
  double limit_mz_range_start)
{
  m_limitMzRangeStart = limit_mz_range_start;
}


double
BaseMsRunDataSetTreeNodeVisitor::getLimitMzRangeStart() const
{
  return m_limitMzRangeStart;
}


void
BaseMsRunDataSetTreeNodeVisitor::setLimitMzRangeEnd(double limit_mz_range_end)
{
  m_limitMzRangeEnd = limit_mz_range_end;
}


double
BaseMsRunDataSetTreeNodeVisitor::getLimitMzRangeEnd() const
{
  return m_limitMzRangeEnd;
}


BaseMsRunDataSetTreeNodeVisitor &
BaseMsRunDataSetTreeNodeVisitor::operator=(
  const BaseMsRunDataSetTreeNodeVisitor &other)
{
  if(this == &other)
    return *this;

  mcsp_msRunDataSet = other.mcsp_msRunDataSet;
  m_processingFlow  = other.m_processingFlow;

  m_limitMzRangeStart = other.m_limitMzRangeStart;
  m_limitMzRangeEnd   = other.m_limitMzRangeEnd;

  return *this;
}


pappso::QualifiedMassSpectrumCstSPtr
BaseMsRunDataSetTreeNodeVisitor::checkQualifiedMassSpectrum(
  const pappso::MsRunDataSetTreeNode &node)
{
  pappso::QualifiedMassSpectrumCstSPtr qualified_mass_spectrum_csp =
    node.getQualifiedMassSpectrum();

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

  if(qualified_mass_spectrum_csp->getMassSpectrumSPtr() == nullptr)
    {
      // qDebug() << "Need to access the mass data right from the file.";

      std::size_t mass_spectrum_index =
        mcsp_msRunDataSet->getMsRunDataSetTreeCstSPtr()->massSpectrumIndex(
          &node);

      pappso::MsRunReaderCstSPtr ms_run_reader_csp =
        mcsp_msRunDataSet->getMsRunReaderCstSPtr();

      // Node the true bool value to indicate that we want the mz,i binary data.

      qualified_mass_spectrum_csp =
        std::make_shared<pappso::QualifiedMassSpectrum>(
          ms_run_reader_csp->qualifiedMassSpectrum(mass_spectrum_index, true));
    }

  if(qualified_mass_spectrum_csp == nullptr)
      qFatal("QualifiedMassSpectrum cannot be nullptr.");
  
  //qDebug() << "Retention time is:" << qualified_mass_spectrum_csp->getRtInMinutes();

  // In some cases this might happen, for example with the Leptocheline_MS3_DDA_IT_1.mzml
  // test file.
  
  //if(!qualified_mass_spectrum_csp->size())
    //qFatal("The qualified mass spectrum is empty (size is 0).");

  return qualified_mass_spectrum_csp;
}


bool
BaseMsRunDataSetTreeNodeVisitor::checkMsLevel(
  const pappso::MsRunDataSetTreeNode &node)
{

  // Immediately get a pointer to  the qualified mass spectrum that is stored
  // in the node.

  // qDebug().noquote() << "Visiting node:" << &node << "text format:" <<
  // node.toString()
  //<< "with quaified mass spectrum:"
  //<< node.getQualifiedMassSpectrum()->toString();

  pappso::QualifiedMassSpectrumCstSPtr qualified_mass_spectrum_csp =
    node.getQualifiedMassSpectrum();

  uint spectrum_ms_level = qualified_mass_spectrum_csp->getMsLevel();

  // qDebug().noquote() << "Current mass spectrum has ms level:"
  //<< spectrum_ms_level;

  // Get the greatest MS level that is requested amongst all the steps/specs in
  // the processing flow. We are not going going to accept a mass spectrum with
  // a differing MS level.

  size_t greatest_ms_level = m_processingFlow.greatestMsLevel();

  // qDebug().noquote() << "Greatest ms level in the processing flow:"
  //<< greatest_ms_level;

  // Check if the mass spectrum matches the requirement about the MS level. Note
  // that if the greatest MS level is 0, then we account for all data because
  // that means that the MS level is not a criterion for filtering mass spectra
  // during the visit of the ms run data set tree.

  if(greatest_ms_level)
    {
      if(spectrum_ms_level != greatest_ms_level)
        {
          // qDebug().noquote()
          //<< "Spectrum ms level:" << spectrum_ms_level
          //<< "does *not* match greatestest ms level:" << greatest_ms_level;

          return false;
        }
      else
        {
          // qDebug().noquote()
          //<< "Spectrum ms level:" << spectrum_ms_level
          //<< "*does* match greatestest ms level:" << greatest_ms_level;
        }
    }
  else
    {
      // qDebug() << "The greatest ms level is 0, accounting all the spectra.";
      // Just go on, we do take into consideration any MS level.
    }

  return true;
}


void
BaseMsRunDataSetTreeNodeVisitor::cancelOperation()
{
  m_isOperationCancelled = true;

  // qDebug() << "The visitor has got a cancelOperationSignal, setting "
  //"m_isOperationCancelled to true.";
}


void
BaseMsRunDataSetTreeNodeVisitor::setNodesToProcessCount(
  std::size_t nodes_to_process)
{
  // qDebug() << "emitting increment nodes to process:" << nodes_to_process;

  // Since this visitor might be running in a thread, along with other threads,
  // we do not want to set the max progress bar value to only the number of
  // nodes that are going to be processed in the current thread. So we tell the
  // user of the visitor that we are only telling how many nodes are to be
  // processed in this thread. The user will increment the total count to
  // nodes_to_process. In a typical setting, the immediate user of this signal
  // is the MassDataIntegrator.
  emit incrementProgressBarMaxValueSignal(nodes_to_process);
}


bool
BaseMsRunDataSetTreeNodeVisitor::shouldStop() const
{
  // qDebug() << "returning" << m_isOperationCancelled;

  return m_isOperationCancelled;
}


void
BaseMsRunDataSetTreeNodeVisitor::silenceFeedback(bool silence_feedback)
{
  m_isProgressFeedbackSilenced = silence_feedback;
}


bool
BaseMsRunDataSetTreeNodeVisitor::shouldSilenceFeedback()
{
  return m_isProgressFeedbackSilenced;
}

} // namespace minexpert

} // namespace msxps
