/*
    libmaus2
    Copyright (C) 2021 German Tischler-Höhle

    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_PARALLEL_THREADPOOL_BAM_BAMPARSECONTEXT_HPP)
#define LIBMAUS2_PARALLEL_THREADPOOL_BAM_BAMPARSECONTEXT_HPP

#include <libmaus2/parallel/threadpool/bam/BamParseOutputQueue.hpp>
#include <libmaus2/parallel/threadpool/bam/BamParseHeaderData.hpp>

namespace libmaus2
{
	namespace parallel
	{
		namespace threadpool
		{
			namespace bam
			{
				struct BamParseContext : public BamParseOutputQueue, public BamParseHeaderData
				{
					libmaus2::util::atomic_shared_ptr<char[]> putback;
					std::atomic<std::size_t> putback_n;
					std::atomic<std::size_t> putback_f;
					std::atomic<std::size_t> numalgn;
					std::atomic<std::size_t> numalgnprnt;

					BamParseContext()
					: putback(), putback_n(0), putback_f(0), numalgn(0), numalgnprnt(0)
					{

					}

					void bumpPutback()
					{
						std::size_t const old_n = putback_n.load();
						std::size_t const new_n = old_n ? (2*old_n) : 1;

						libmaus2::util::shared_ptr<char[]> ptr(new char[new_n]);
						libmaus2::util::shared_ptr<char[]> optr(putback.load());

						char * const to   = ptr.get();
						char *       from = optr.get();

						std::copy(from,from+old_n,to);

						putback.store(ptr);
						putback_n.store(new_n);
					}

					void addPutback(char const * ca, char const * ce)
					{
						std::ptrdiff_t const req = putback_f.load() + (ce-ca);

						while ( req > static_cast<std::ptrdiff_t>(putback_n.load()) )
							bumpPutback();

						char * const to = putback.load().get() + putback_f.load();

						std::copy(ca,ce,to);

						putback_f += (ce-ca);
					}

					void setPutback(char const * ca, char const * ce)
					{
						std::ptrdiff_t const f = ce - ca;

						while ( f > static_cast<std::ptrdiff_t>(putback_n.load()) )
							bumpPutback();

						char * const to = putback.load().get();

						std::copy(ca,ce,to);

						putback_f.store(f);
					}
				};
			}
		}
	}
}
#endif
