/*
    libmaus2
    Copyright (C) 2019 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_BAMNUMEXTRACTOR_HPP)
#define LIBMAUS2_BAMBAM_BAMNUMEXTRACTOR_HPP

#include <libmaus2/lz/BgzfInflateBase.hpp>
#include <libmaus2/lz/BgzfDeflateZStreamBase.hpp>
#include <libmaus2/lz/BgzfDeflate.hpp>

#include <libmaus2/bambam/BamDecoder.hpp>
#include <libmaus2/bambam/BamNumericalIndexDecoder.hpp>
#include <libmaus2/bambam/BamNumericalIndexGenerator.hpp>

namespace libmaus2
{
	namespace bambam
	{
		struct BamNumExtractor
		{
			std::string const bamfn;
			libmaus2::bambam::BamNumericalIndexDecoder::unique_ptr_type indexdec;
			libmaus2::bambam::BamHeader::unique_ptr_type pheader;

			static libmaus2::bambam::BamNumericalIndexDecoder::unique_ptr_type openIndex(std::string const & bamfn)
			{
				std::string const indexfn = libmaus2::bambam::BamNumericalIndexBase::getIndexName(bamfn);
				libmaus2::bambam::BamNumericalIndexGenerator::indexFileCheck(bamfn,indexfn,1024 /* mod */,1 /* numthreads */,true /* verbose */);

				libmaus2::bambam::BamNumericalIndexDecoder::unique_ptr_type tptr(
					new libmaus2::bambam::BamNumericalIndexDecoder(
						indexfn
					)
				);

				return tptr;
			}

			BamNumExtractor(std::string const & rbamfn)
			: bamfn(rbamfn), indexdec(openIndex(bamfn))
			{
				libmaus2::bambam::BamDecoder dec(bamfn);
				libmaus2::bambam::BamHeader::unique_ptr_type theader(dec.getHeader().uclone());
				pheader = std::move(theader);
			}

			void extract(std::string const & fn, int const level, uint64_t from, uint64_t to)
			{
				libmaus2::aio::OutputStreamInstance OSI(fn);
				extract(OSI,level,from,to);
			}

			void extract(std::ostream & out, int const level, uint64_t from, uint64_t to)
			{
				if ( to > indexdec->getAlignmentCount() )
					to = indexdec->getAlignmentCount();

				{
					libmaus2::lz::BgzfDeflate<std::ostream> BD(out,level);
					pheader->serialise(BD);
					BD.flush();
				}

				if ( to > from )
				{
					std::pair<uint64_t,uint64_t> ufrom;
					std::pair<uint64_t,uint64_t> uto;

					{
						libmaus2::bambam::BamRawDecoder::unique_ptr_type dec0(
							indexdec->getRawDecoderAt(bamfn,from)
						);
						std::pair<
							std::pair<uint8_t const *,uint64_t>,
							libmaus2::bambam::BamRawDecoder::RawInterval
						> const P = dec0->getPos();

						assert ( P.first.first );

						ufrom = P.second.start;
					}

					{
						libmaus2::bambam::BamRawDecoder::unique_ptr_type dec0(
							indexdec->getRawDecoderAt(bamfn,to-1)
						);
						std::pair<
							std::pair<uint8_t const *,uint64_t>,
							libmaus2::bambam::BamRawDecoder::RawInterval
						> const P = dec0->getPos();

						assert ( P.first.first );

						uto = P.second.end;
					}

					// libmaus2::bambam::BamRawDecoder::RawInterval RI(ufrom,uto);
					// std::cerr << "encode " << RI.toString() << std::endl;

					libmaus2::lz::BgzfInflateBase BIS;
					libmaus2::autoarray::AutoArray<uint8_t> B(BIS.getBgzfMaxBlockSize());

					libmaus2::aio::InputStreamInstance ISI(bamfn);
					ISI.clear();
					ISI.seekg(ufrom.first);
					ISI.clear();

					if ( ufrom.first == uto.first )
					{
						libmaus2::lz::BgzfInflateBase::BaseBlockInfo const BBI = BIS.readBlock(ISI);
						BIS.decompressBlock(reinterpret_cast<char *>(B.begin()),BBI);

						{
							libmaus2::lz::BgzfDeflate<std::ostream> BD(out,level);
							BD.write(
								reinterpret_cast<char const *>(B.begin()+ufrom.second),
								uto.second-ufrom.second
							);
							BD.flush();
						}
					}
					else
					{
						libmaus2::lz::BgzfInflateBase::BaseBlockInfo BBI = BIS.readBlock(ISI);
						BIS.decompressBlock(reinterpret_cast<char *>(B.begin()),BBI);

						{
							libmaus2::lz::BgzfDeflate<std::ostream> BD(out,level);
							BD.write(
								reinterpret_cast<char const *>(B.begin()+ufrom.second),
								BBI.uncompdatasize - ufrom.second
							);
							BD.flush();
						}

						uint64_t tocopy = uto.first - (ufrom.first + BBI.compdatasize);

						libmaus2::util::GetFileSize::copy(ISI,out,tocopy);

						BBI = BIS.readBlock(ISI);
						BIS.decompressBlock(reinterpret_cast<char *>(B.begin()),BBI);

						{
							libmaus2::lz::BgzfDeflate<std::ostream> BD(out,level);
							BD.write(
								reinterpret_cast<char const *>(B.begin()),
								uto.second
							);
							BD.flush();
						}
					}
				}

				std::string const eofblock = libmaus2::lz::BgzfDeflate<std::ostream>::getEOFBlock();
				out.write(eofblock.c_str(),eofblock.size());
				out.flush();
			}
		};
	}
}
#endif
