/*
    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/>.
*/
#include <libmaus2/parallel/threadpool/bgzf/DecompressThread.hpp>

namespace libmaus2
{
	namespace parallel
	{
		namespace threadpool
		{
			namespace bam
			{
				struct BamParsePackageData : public libmaus2::parallel::threadpool::ThreadWorkPackageData
				{
					typedef BamParsePackageData this_type;
					typedef std::unique_ptr<this_type> unique_ptr_type;
					typedef std::shared_ptr<this_type> shared_ptr_type;

					std::atomic<libmaus2::parallel::threadpool::input::ThreadPoolInputInfo *> inputinfo;
					libmaus2::parallel::threadpool::bgzf::BgzfBlockInfo::shared_ptr_type blockinfo;
					std::atomic<uint64_t> blockid;
					std::atomic<uint64_t> subid;
					std::atomic<uint64_t> absid;
					std::shared_ptr<char[]> ddata;
					std::atomic<uint64_t> n;
					std::atomic<libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoEnqueDecompressHandler *> decompressHandler;
					std::atomic<libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoProcessor *> processor;

					BamParsePackageData()
					: libmaus2::parallel::threadpool::ThreadWorkPackageData(),
					  inputinfo(nullptr),
					  blockinfo(),
					  blockid(0),
					  subid(0),
					  absid(0),
					  ddata(),
					  n(0),
					  decompressHandler(nullptr),
					  processor(nullptr)
					{

					}

					void dispatch()
					{
						uint64_t const streamid = inputinfo.load()->streamid;

						libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoEnqueDecompressHandler::OutputQueueInfo
							OQI = decompressHandler.load()->getOutputQueue(streamid);

						OQI.push(
							libmaus2::parallel::threadpool::bgzf::BgzfDecompressedBlock(
								blockid,subid,absid,ddata,n,blockinfo
							)
						);

						libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoEnqueDecompressHandler::DecompressWaitingObject & decwa =
							decompressHandler.load()->getDecompressWaiting(streamid);

						libmaus2::parallel::threadpool::bgzf::BgzfDecompressedBlock block;
						while ( OQI.pop(block) )
						{
							decompressHandler.load()->returnBlock(streamid,block.ddata);

							bool const blockcomplete = decwa.incrementDone(block.blockid);
							decompressHandler.load()->TPBRC.BITC.putInfo(
								streamid,block.blockinfo
							);

							OQI.next();
						}
					}
				};


				struct ThreadPoolBamParseControl : public libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoProcessor
				{
					libmaus2::parallel::threadpool::ThreadPool & TP;
					libmaus2::parallel::threadpool::bgzf::ThreadPoolBGZFDecompressControl TPBDC;

					ThreadPoolBamParseControl(
						libmaus2::parallel::threadpool::ThreadPool & rTP,
						std::vector<std::string> const & Vfn
					) : TP(rTP), TPBDC(TP,Vfn)
					{
						TPBDC.setProcessor(this);
					}

					ThreadPoolBamParseControl(
						libmaus2::parallel::threadpool::ThreadPool & rTP,
						std::vector< std::shared_ptr<std::istream> > rVstr
					) : TP(rTP), TPBDC(TP,rVstr)
					{
						TPBDC.setProcessor(this);
					}

					void setDecompressedHandler(
						libmaus2::parallel::threadpool::bgzf::BgzfDataDecompressedInterface * rdecompressedHandler
					)
					{
						TPBDC.setDecompressedHandler(rdecompressedHandler);
					}

					void start()
					{
						TPBDC.start();
					}
				};
			}
		}
	}
}

namespace libmaus2
{
	namespace parallel
	{
		namespace threadpool
		{
			namespace bam
			{
				struct BgzfDataDecompressedBamParseInterface : public libmaus2::parallel::threadpool::bgzf::BgzfDataDecompressedInterface
				{
					virtual void dataDecompressed(
						libmaus2::parallel::threadpool::input::ThreadPoolInputInfo * inputinfo,
						libmaus2::parallel::threadpool::bgzf::BgzfBlockInfo::shared_ptr_type blockinfo,
						uint64_t const blockid,
						uint64_t const subid,
						uint64_t const absid,
						std::shared_ptr<char[]> ddata,
						uint64_t const n,
						libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoEnqueDecompressHandler * decompressHandler,
						libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoProcessor * processor
					)
					{
						uint64_t const streamid = inputinfo->streamid;

						ThreadPoolBamParseControl * PC = dynamic_cast<ThreadPoolBamParseControl *>(processor);
						libmaus2::parallel::threadpool::ThreadPool & TP = decompressHandler->TP;

						libmaus2::parallel::threadpool::ThreadWorkPackage::shared_ptr_type pack(TP.getPackage<BamParsePackageData>());
						BamParsePackageData * data = dynamic_cast<BamParsePackageData *>(pack->data.get());

						data->inputinfo = inputinfo;
						data->blockinfo = blockinfo;
						data->blockid = blockid;
						data->subid = subid;
						data->absid = absid;
						data->ddata = ddata;
						data->n = n;
						data->decompressHandler = decompressHandler;
						data->processor = processor;

						TP.enqueue(pack);

						#if 0
						libmaus2::parallel::threadpool::bgzf::BgzfBlockInfoEnqueDecompressHandler::OutputQueueInfo OQI = decompressHandler->getOutputQueue(streamid);

						OQI.push(libmaus2::parallel::threadpool::bgzf::BgzfDecompressedBlock(blockid,subid,absid,ddata,n));

						libmaus2::parallel::threadpool::bgzf::BgzfDecompressedBlock block;
						while ( OQI.pop(block) )
						{
							decompressHandler->returnBlock(block.ddata);
							OQI.next();
						}

						uint64_t const lfinished = ++(decompressHandler->getAbsBlockFinished(streamid));

						if (
							decompressHandler->TPBRC.BITC.parseFinished(streamid)
							&&
							lfinished == decompressHandler->getAbsBlock(inputinfo->streamid).load()
						)
						{
							std::cerr << "stream decomp finished " << streamid << std::endl;

							uint64_t const nfinished = ++decompressHandler->numStreamsDecompressFinished;

							if ( nfinished == decompressHandler->numstreams )
							{
								decompressHandler->TP.terminate();
							}
						}
						#endif
					}
				};

			}
		}
	}
}

namespace libmaus2
{
	namespace parallel
	{
		namespace threadpool
		{
			namespace bam
			{
				struct BamParsePackageDataDispatcher : public libmaus2::parallel::threadpool::ThreadPoolDispatcher
				{
					virtual void dispatch(libmaus2::parallel::threadpool::ThreadWorkPackage & package, libmaus2::parallel::threadpool::ThreadPool * /* pool */)
					{
						BamParsePackageData * data = dynamic_cast<BamParsePackageData *>(package.data.get());
						data->dispatch();

						/*
						BgzfBlockInfoEnqueDecompressHandler * handler = data->decompHandler;
						handler->decompressData(package.data);
						*/
					}
				};
			}
		}
	}
}


#include <libmaus2/util/ArgParser.hpp>
#include <libmaus2/aio/StreamLock.hpp>

int main(int argc, char * argv[])
{
	try
	{
		libmaus2::util::ArgParser arg(argc,argv);

		std::vector<std::string> Vfn;
		for ( uint64_t i = 0; i < arg.size(); ++i )
			Vfn.push_back(arg[i]);

		if ( ! Vfn.size() )
		{
			std::cerr << "[E] need at least one input file name" << std::endl;
			return EXIT_FAILURE;
		}

		libmaus2::parallel::threadpool::ThreadPool TP(12);

		libmaus2::parallel::threadpool::bam::ThreadPoolBamParseControl TPBDC(TP,Vfn);

		libmaus2::parallel::threadpool::bam::BgzfDataDecompressedBamParseInterface BDDTRH;
		TPBDC.setDecompressedHandler(&BDDTRH);

		TP.registerDispatcher<libmaus2::parallel::threadpool::bam::BamParsePackageData>(
			std::shared_ptr<libmaus2::parallel::threadpool::ThreadPoolDispatcher>(
				new libmaus2::parallel::threadpool::bam::BamParsePackageDataDispatcher
			)
		);


		TPBDC.start();

		TP.join();

		std::cerr << "[V] finished and joined" << std::endl;
	}
	catch(std::exception const & ex)
	{
		std::cerr << ex.what() << std::endl;
		return EXIT_FAILURE;
	}
}
