/*
    libmaus2
    Copyright (C) 2018 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_DAZZLER_DB_IQVDECODER_HPP)
#define LIBMAUS2_DAZZLER_DB_IQVDECODER_HPP

#include <libmaus2/dazzler/db/DatabaseFile.hpp>

namespace libmaus2
{
	namespace dazzler
	{
		namespace db
		{
			struct IQVDecoder
			{
				libmaus2::dazzler::db::Track const & track;
				libmaus2::dazzler::db::TrackAnnoInterface const & anno;
				int64_t const tspace;
				std::vector<uint64_t> const & RL;

				IQVDecoder(libmaus2::dazzler::db::Track const & rtrack, int64_t const rtspace, std::vector<uint64_t> const & rRL)
				: track(rtrack), anno(track.getAnno()), tspace(rtspace), RL(rRL)
				{}

				unsigned char getQualityForBlock(uint64_t const read, uint64_t const block) const
				{
					if ( read < RL.size() )
					{
						uint64_t const tqa = anno[read];
						unsigned char const * Du = track.Adata->begin() + tqa;
						return Du[block];
					}
					else
					{
						libmaus2::exception::LibMausException lme;
						lme.getStream() << "[E] IQVDecoder::getQualityForBlock(" << read << "," << block << "): unknown read id" << std::endl;
						lme.finish();
						throw lme;
					}
				}

				unsigned char getQualityForInterval(uint64_t const read, uint64_t const low, uint64_t const high) const
				{
					uint64_t const blocklow = low / tspace;
					uint64_t const blockhigh = (high-1)/tspace;

					if ( blockhigh >= blocklow )
					{
						unsigned char u = getQualityForBlock(read,blocklow);

						for ( uint64_t i = blocklow+1; i <= blockhigh; ++i )
							u = std::max(u,getQualityForBlock(read,i));

						return u;
					}
					else
					{
						return std::numeric_limits<unsigned char>::max();
					}
				}

				unsigned char getQualityForInterval(uint64_t const read, uint64_t low, uint64_t high, bool const inv) const
				{
					if ( inv )
					{
						std::swap(low,high);
						low = RL[read]-low;
						high = RL[read]-high;
					}

					return getQualityForInterval(read,low,high);
				}
			};
		}
	}
}
#endif
