/**
    bambam
    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/>.
**/
#include <config.h>

#include <libmaus2/vcf/VCFParser.hpp>
#include <libmaus2/util/ArgInfo.hpp>
#include <libmaus2/lz/BgzfDeflate.hpp>
#include <libmaus2/fastx/FastAReader.hpp>

#include <biobambam2/Licensing.hpp>

static int getDefaultVerbose() { return 0; }

int vcfreplacecontigs(libmaus2::util::ArgInfo const & arginfo, std::istream & in, std::ostream & out)
{
	//unsigned int const verbose = arginfo.getValue<unsigned int>("verbose",getDefaultVerbose());
	bool const gz = arginfo.getValue<int>("gz",0);

	libmaus2::lz::BgzfOutputStream::unique_ptr_type pBOS;

	if ( gz )
	{
		libmaus2::lz::BgzfOutputStream::unique_ptr_type tBOS(new libmaus2::lz::BgzfOutputStream(out));
		pBOS = std::move(tBOS);
	}

	std::ostream & vout = gz ? *pBOS : out;

	libmaus2::vcf::VCFParser vcf(in);

	if ( ! ( 0 < arginfo.getNumRestArgs() ) )
	{
		std::cerr << "[E] usage: " << arginfo.progname << " <in.fa> <in.vcf" << std::endl;
		return EXIT_FAILURE;
	}

	std::string const fafn = arginfo.getUnparsedRestArg(0);
	std::vector<libmaus2::bambam::Chromosome> V;
	std::set<std::string> S;
	{
		libmaus2::fastx::FastAReader FA(fafn);
		libmaus2::fastx::FastAReader::pattern_type pat;
		while ( FA.getNextPatternUnlocked(pat) )
		{
			std::string const name = pat.getShortStringId();
			V.push_back(libmaus2::bambam::Chromosome(name,pat.spattern.size()));
			S.insert(name);
			std::cerr << "[V] pushed " << name << "[" << pat.spattern.size() << "]" << std::endl;
		}
	}

	vcf.setChromosomeVector(V);
	vcf.printText(vout);


	std::pair<
        	libmaus2::util::TabEntry<> const *,
                char const *
	> P;

	std::pair<
		std::vector<std::string>,
		::libmaus2::trie::LinearHashTrie<char,uint32_t>::shared_ptr_type
	> const Pcontig = vcf.getContigNamesAndTrie();

	uint64_t line = 0;
	while ( (P = vcf.readEntry()).first )
	{
		if ( P.first->size() )
		{
			std::pair<char const *, char const *> const Pchr = P.first->get(0,P.second);

			if ( Pcontig.second->searchCompleteNoFailure(Pchr.first,Pchr.second) != -1 )
			{
				char const * a = P.first->get(0,P.second).first;
				char const * e = P.first->get(P.first->size()-1,P.second).second;

				vout.write(a,e-a);
				vout.put('\n');

				line += 1;

				if ( line % (1024*1024) == 0 )
					std::cerr << "[V] " << line << std::endl;
			}
			else
			{
				libmaus2::exception::LibMausException lme;
				lme.getStream() << "[E] sequence " << std::string(Pchr.first,Pchr.second) << " does not appear in FastA file provided" << std::endl;
				lme.finish();
				throw lme;
			}
		}
	}

	// vcf.unparsedCopy(vout);

	#if 0
	if ( Vin.size() )
	{
		std::pair<bool, char const *> E;

		{
			libmaus2::aio::InputStreamInstance ISI(Vin[0]);
			libmaus2::vcf::VCFParser vcf(ISI);
			vcf.printText(vout);
			vcf.unparsedCopy(vout);
		}

		for ( uint64_t j = 1; j < Vin.size(); ++j )
		{
			libmaus2::aio::InputStreamInstance ISI(Vin[j]);
			libmaus2::vcf::VCFParser vcf(ISI);
			vcf.unparsedCopy(vout);
		}
	}
	#endif

	if ( gz )
	{
		pBOS->flush();
		pBOS->addEOFBlock();
		pBOS.reset();
	}

	return EXIT_SUCCESS;
}

int main(int argc, char * argv[])
{
	try
	{
		::libmaus2::util::ArgInfo const arginfo(argc,argv);

		for ( uint64_t i = 0; i < arginfo.restargs.size(); ++i )
			if (
				arginfo.restargs[i] == "-v"
				||
				arginfo.restargs[i] == "--version"
			)
			{
				std::cerr << ::biobambam2::Licensing::license();
				return EXIT_SUCCESS;
			}
			else if (
				arginfo.restargs[i] == "-h"
				||
				arginfo.restargs[i] == "--help"
			)
			{
				std::cerr << ::biobambam2::Licensing::license();
				std::cerr << std::endl;
				std::cerr << "Key=Value pairs:" << std::endl;
				std::cerr << std::endl;

				std::vector< std::pair<std::string,std::string> > V;

				V.push_back ( std::pair<std::string,std::string> ( "verbose=<["+::biobambam2::Licensing::formatNumber(getDefaultVerbose())+"]>", "print progress report (default: 1)" ) );

				::biobambam2::Licensing::printMap(std::cerr,V);

				std::cerr << std::endl;
				return EXIT_SUCCESS;
			}

		return vcfreplacecontigs(arginfo,std::cin,std::cout);
	}
	catch(std::exception const & ex)
	{
		std::cerr << ex.what() << std::endl;
		return EXIT_FAILURE;
	}
}
