/**
 * \file pappsomspp/core/processing/cbor/mzcbor/scan.cpp
 * \date 03/02/2026
 * \author Olivier Langella
 * \brief PSI scan object for mzML/mzCBOR
 */

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


#include "scan.h"
#include "pappsomspp/core/exception/exceptionnotfound.h"


double
pappso::cbor::mzcbor::Scan::getRtInSeconds() const
{
  //            <cvParam cvRef="MS" accession="MS:1000016" value="0.0048758833" name="scan start
  //            time" unitAccession="UO:0000031" unitName="minute" unitCvRef="UO" />

  auto it = cvParamMap.find("MS:1000016");
  if(it == cvParamMap.end())
    {
      throw pappso::ExceptionNotFound(QObject::tr("retention time not found in cvParam map"));
    }
  double rt_seconds = it->second.valueDouble;
  if(it->second.unitAccession == "UO:0000031")
    {
      // // minutes
      rt_seconds = rt_seconds * 60;
    }

  //              <cvParam cvRef="MS" accession="MS:1000016" value="0" name="scan start time"
  //              unitAccession="UO:0000031" unitName="minute" unitCvRef="UO" />
  return rt_seconds;
}

void
pappso::cbor::mzcbor::Scan::fromCbor(CborStreamReader &reader)
{

  QString txt_value;
  reader.enterContainer();
  qDebug() << txt_value;
  while(reader.hasNext() && (!reader.isInvalid()))
    {
      if(reader.isString())
        {
          if(reader.decodeString(txt_value))
            {
              qDebug() << txt_value;
              if(txt_value == "cvParam")
                {
                  // precursorListCvParamMap = CvParam::getCvParamsMapFromCbor(reader);
                  cvParamMap.fromCbor(reader);
                }
              else
                {
                  reader.next();
                }
            }
          else
            {
              reader.next();
            }
        }
      else
        {
          reader.next();
        }
    }
  reader.leaveContainer();
}


QJsonObject
pappso::cbor::mzcbor::Scan::toJsonObject() const
{
  QJsonObject scan;
  scan.insert("cvParam", cvParamMap.toJsonArray());
  return scan;
}
