/**
 * \file pappsomspp/vendors/tims/timsframe.h
 * \date 23/08/2019
 * \author Olivier Langella
 * \brief handle a single Bruker's TimsTof frame
 */

/*******************************************************************************
 * Copyright (c) 2019 Olivier Langella <Olivier.Langella@u-psud.fr>.
 *
 * This file is part of the PAPPSOms++ library.
 *
 *     PAPPSOms++ 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++ 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++.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#pragma once

#include <memory>
#include <QByteArray>
#include <vector>
#include "timsframebase.h"
#include "../../xic/xic.h"
#include "../../msrun/xiccoord/xiccoordtims.h"


namespace pappso
{

class TimsFrame;
typedef std::shared_ptr<TimsFrame> TimsFrameSPtr;
typedef std::shared_ptr<const TimsFrame> TimsFrameCstSPtr;

class TimsBinDec;

class TimsDirectXicExtractor;

/**
 * @todo write docs
 */
class TimsFrame : public TimsFrameBase
{
  friend TimsDirectXicExtractor;

  public:
  /**
   * @param timsId tims frame id
   * @param scanNum total number of scans in this frame
   * @param p_bytes pointer on the decompressed binary buffer
   * @param len size of the decompressed binary buffer
   */
  TimsFrame(std::size_t timsId,
            quint32 scanNum,
            char *p_bytes,
            std::size_t len);
  /**
   * Copy constructor
   *
   * @param other TODO
   */
  TimsFrame(const TimsFrame &other);

  /**
   * Destructor
   */
  virtual ~TimsFrame();


  virtual std::size_t getScanPeakCount(std::size_t scanIndex) const override;

  /** @brief cumulate scan list into a trace
   * @param scanNumBegin first scan to cumulate
   * @param scanNumEnd last scan to cumulate
   * @return Trace mz and intensity values
   */
  virtual Trace cumulateScansToTrace(std::size_t scanIndexBegin,
                                     std::size_t scanIndexEnd) const override;


  /** @brief cumulate spectrum given a scan number range
   * need the binary file
   * The intensities are normalized with respect to the frame accumulation time
   * to leverage computing performance, this function decreases the mz
   * resolution
   *
   * @param mzindex_merge_window width of the mzindex window used to merge all
   * intensities into a single point. This results in faster computing.
   * @param scanNumBegin scan number in the frame in the order it lies in binary
   * file, from 0 to N-1
   * @param scanNumEnd scan number in the frame in the order it lies in binary
   * file, from 0 to N-1
   * @param mz_minimum_index report the minimum mz index contained in the
   * resulting trace
   * @param mz_maximum_index report the maximum mz index contained in the
   * resulting trace
   *
   */
  virtual Trace combineScansToTraceWithDowngradedMzResolution(
    std::size_t mzindex_merge_window,
    std::size_t scanNumBegin,
    std::size_t scanNumEnd,
    quint32 &mz_minimum_index,
    quint32 &mz_maximum_index) const override;


  /** @brief cumulate spectrum given a scan number range
   * need the binary file
   * The intensities are normalized with respect to the frame accumulation time
   * to leverage computing performance, this function decreases the mz
   * resolution
   *
   * @param mzindex_merge_window width of the mzindex window used to merge all
   * intensities into a single point. This results in faster computing.
   * @param mz_range_begin
   * @param mz_range_end
   * @param scanNumBegin scan number in the frame in the order it lies in binary
   * file, from 0 to N-1
   * @param scanNumEnd scan number in the frame in the order it lies in binary
   * file, from 0 to N-1
   * @param mz_minimum_index report the minimum mz index contained in the
   * resulting trace (constrained by the mz_range_begin)
   * @param mz_maximum_index report the maximum mz index contained in the
   * resulting trace (constrained by the mz_range_end)
   *
   */
  virtual Trace combineScansToTraceWithDowngradedMzResolution2(
    std::size_t mz_index_merge_window,
    double mz_range_begin,
    double mz_range_end,
    std::size_t mobility_scan_begin,
    std::size_t mobility_scan_end,
    quint32 &mz_minimum_index_out,
    quint32 &mz_maximum_index_out) const override;

  /** @brief cumulate scan list into a trace into a raw spectrum map
   * @param rawSpectrum simple map of integers to cumulate raw counts
   * @param scanNumBegin first scan to cumulate
   * @param scanNumEnd last scan to cumulate
   */
  void
  combineScansInTofIndexIntensityMap(TimsDataFastMap &rawSpectrum,
                                     std::size_t scan_index_begin,
                                     std::size_t scan_index_end) const override;
                                     
                                      virtual void
  combineScansInTofIndexIntensityMap(TimsDataFastMap &tof_index_intensity_map,
                                     std::size_t scan_index_begin,
                                     std::size_t scan_index_end,
                                     quint32 tof_index_begin,
                                     quint32 tof_index_end) const override;



  /** @brief get a single mobility scan m/z + intensities
   *
   * @param scanNum scan number in the frame in the order it lies in binary
   * file, from 0 to N-1
   * @param mzindex_merge_window width of the mzindex window used to merge all
   * intensities into a single point. This results in faster computing.
   * @param mz_range_begin
   * @param mz_range_end
   * @param mz_minimum_index report the minimum mz index contained in the
   * resulting trace (constrained by the mz_range_begin)
   * @param mz_maximum_index report the maximum mz index contained in the
   * resulting trace (constrained by the mz_range_end)
   *
   */
  virtual Trace getMobilityScan(std::size_t scanNum,
                                std::size_t mz_index_merge_window,
                                double mz_range_begin,
                                double mz_range_end,
                                quint32 &mz_minimum_index_out,
                                quint32 &mz_maximum_index_out) const override;

  virtual quint64 cumulateScanIntensities(std::size_t scanNum) const override;

  virtual quint64
  cumulateScanRangeIntensities(std::size_t scanNumBegin,
                               std::size_t scanNumEnd) const override;

  /** @brief get raw index list for one given scan
   * index are not TOF nor m/z, just index on digitizer
   */
  virtual std::vector<quint32>
  getScanTofIndexList(std::size_t scanNum) const override;

  /** @brief get raw intensities without transformation from one scan
   * it needs intensity normalization
   */
  virtual std::vector<quint32>
  getScanIntensityList(std::size_t scanNum) const override;

  virtual pappso::MassSpectrumSPtr
  getMassSpectrumSPtr(std::size_t scanNum) const override;


  /** @brief get the raw index tof_index and intensities (normalized)
   *
   * @param scanNum the scan number to extract
   * @param accepted_tof_index_range_begin mz index begin
   * @param accepted_tof_index_range_end mz index end
   * @return vector of RawValuePair
   *
   */
  virtual std::vector<TofIndexIntensityPair>
  getRawValuePairList(std::size_t scanNum,
                      quint32 accepted_tof_index_range_begin,
                      quint32 accepted_tof_index_range_end) const;

  protected:
  /** @brief constructor for binary independant tims frame
   * @param timsId tims frame identifier in the database
   * @param scanNum the total number of scans contained in this frame
   */
  TimsFrame(std::size_t timsId, quint32 scanNum);

  void extractTimsXicListInRtRange(
    std::vector<XicCoordTims *>::iterator &itXicListbegin,
    std::vector<XicCoordTims *>::iterator &itXicListend,
    XicExtractMethod method) const;


  /** @brief cumulate a scan into a map
   *
   * @param scanNum scan number 0 to (m_scanNumber-1)
   */
  virtual void cumulateScan(std::size_t scanNum,
                            TimsDataFastMap &accumulate_into) const;


  virtual void cumulateScan2(std::size_t scanNum,
                             TimsDataFastMap &accumulate_into,
                             quint32 accepted_tof_index_range_begin,
                             quint32 accepted_tof_index_range_end) const;

  /** @brief get the raw index tof_index and intensities (normalized)
   *
   * @param scanNum the scan number to extract
   * @return trace vector
   *
   */
  virtual pappso::TraceSPtr getRawTraceSPtr(std::size_t scanNum) const;


  private:
  /** @brief unshuffle data packet of tims compression type 2
   * @param src is a zstd decompressed buffer pointer
   */
  void unshufflePacket(const char *src);


  /** @brief get offset for this spectrum in the binary file
   *
   * @param scanNum scan number in the frame in the order it lies in binary
   * file, from 0 to N-1
   */

  std::size_t getScanOffset(std::size_t scanNum) const;

  private:
  struct XicComputeStructure
  {
    XicComputeStructure(const TimsFrame *fram_p,
                        const XicCoordTims &xic_struct);


    Xic *xic_ptr = nullptr;
    std::size_t mobilityIndexBegin;
    std::size_t mobilityIndexEnd;
    std::size_t mzIndexLowerBound;
    std::size_t mzIndexUpperBound;
    double tmpIntensity = 0;
  };

  protected:
  QByteArray m_binaryData;
};
} // namespace pappso
