/*
    libmaus2
    Copyright (C) 2020 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_BGZF_GENERICBLOCK_HPP)
#define LIBMAUS2_PARALLEL_THREADPOOL_BGZF_GENERICBLOCK_HPP

#include <libmaus2/parallel/threadpool/input/ThreadPoolInputInfo.hpp>
#include <libmaus2/parallel/AtomicStack.hpp>

namespace libmaus2
{
	namespace parallel
	{
		namespace threadpool
		{
			namespace bgzf
			{
				struct BgzfBlockInfoEnqueDecompressHandler;

				struct GenericBlock
				{
					libmaus2::util::atomic_shared_ptr<char[]> B;
					std::atomic<std::size_t> o;
					std::atomic<std::size_t> n;
					std::atomic<std::size_t> f;
					libmaus2::parallel::AtomicStack<char const *> P;
					std::atomic<std::size_t> streamid;
					std::atomic<std::size_t> absid;
					std::atomic<BgzfBlockInfoEnqueDecompressHandler *> decompressHandler;
					std::atomic<bool> eof;
					std::atomic<libmaus2::parallel::threadpool::input::ThreadPoolInputInfo *> inputinfo;

					GenericBlock(std::size_t const rn)
					: B(libmaus2::util::shared_ptr<char[]>(new char[rn])), o(0), n(rn), f(0), P(), streamid(0), absid(0), decompressHandler(nullptr) {}

					bool operator<(GenericBlock const & G) const
					{
						return absid.load() < G.absid.load();
					}

					void prepend(char const * ca, char const * ce)
					{
						assert ( o.load() + f.load() == n.load() );

						std::ptrdiff_t const req = ce - ca;

						if ( req > static_cast<std::ptrdiff_t>(o.load()) )
						{
							std::size_t const n_n = f.load() + req;
							assert ( n_n > n.load() );

							// new memory
							libmaus2::util::shared_ptr<char[]> tptr(new char[n_n]);

							std::size_t const n_o = n_n - f.load();

							std::copy(
								B.load().get() + o.load(),
								B.load().get() + o.load() + f.load(),
								tptr.get() + n_o
							);

							o.store(n_o);
							n.store(n_n);
							B.store(tptr);
						}

						assert ( static_cast<std::ptrdiff_t>(o.load()) >= req );

						o -= req;
						f += req;

						std::copy(ca,ce,B.load().get() + o.load());
					}
				};
			}
		}
	}
}
#endif
