/*
    libmaus2
    Copyright (C) 2016 German Tischler

    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/>.
*/
#if ! defined(LIBMAUS2_BAMBAM_BAMRAWPEEKER_HPP)
#define LIBMAUS2_BAMBAM_BAMRAWPEEKER_HPP

#include <libmaus2/bambam/BamRawDecoder.hpp>

namespace libmaus2
{
	namespace bambam
	{
		struct BamRawPeeker
		{
			libmaus2::bambam::BamRawDecoder * dec;
			std::pair<uint8_t const *, std::size_t> P;
			bool slotfilled;
			int64_t limit;
			int64_t proc;

			bool getNextRaw()
			{
				if ( limit >= 0 && proc == limit )
					return false;

				P = dec->get();

				if ( ! P.first )
					return false;

				proc += 1;

				return true;
			}

			BamRawPeeker(libmaus2::bambam::BamRawDecoder * const rdec, int64_t const rlimit = -1)
			: dec(rdec), P(nullptr,0), slotfilled(false), limit(rlimit), proc(0) {}

			bool getNext(libmaus2::bambam::BamAlignment & ralgn)
			{
				if ( ! slotfilled )
					slotfilled = getNextRaw();
				if ( ! slotfilled )
					return false;

				ralgn.D.ensureSize(P.second);
				std::copy(P.first,P.first + P.second,ralgn.D.begin());
				ralgn.blocksize = P.second;
				slotfilled = false;
				return true;
			}

			bool peekNext(libmaus2::bambam::BamAlignment & ralgn)
			{
				if ( ! slotfilled )
					slotfilled = getNextRaw();
				if ( ! slotfilled )
					return false;

				ralgn.D.ensureSize(P.second);
				std::copy(P.first,P.first+P.second,ralgn.D.begin());
				ralgn.blocksize = P.second;
				return true;
			}
		};
	}
}
#endif
