/*
    libmaus2
    Copyright (C) 2020 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 <libmaus2/network/CurlInputStreamBuffer.hpp>

libmaus2::network::CurlInputStreamBuffer::CurlInputStreamBuffer(std::string const & url, std::size_t const rblocksize, std::size_t const rputbackspace)
:
  COR(url),
  blocksize(rblocksize),
  putbackspace(rputbackspace),
  buffer(putbackspace + blocksize,false)
{
	setg(buffer.end(), buffer.end(), buffer.end());
}

libmaus2::network::CurlInputStreamBuffer::int_type libmaus2::network::CurlInputStreamBuffer::underflow()
{
	if ( gptr() < egptr() )
		return static_cast<int_type>(*(reinterpret_cast<uint8_t const *>(gptr())));

	::std::size_t const pbcopy = std::min(static_cast<::std::size_t>(gptr()-eback()),static_cast<std::size_t>(putbackspace));

	std::memmove(buffer.begin() + putbackspace - pbcopy,gptr()-pbcopy,pbcopy);

	::std::size_t const n = COR.read(buffer.begin()+putbackspace,buffer.size()-putbackspace);

	setg(
		buffer.begin()+putbackspace-pbcopy,
		buffer.begin()+putbackspace,
		buffer.begin()+putbackspace+n
	);

	if ( n )
		return static_cast<int_type>(*(reinterpret_cast<uint8_t const *>(gptr())));
	else
		return traits_type::eof();
}
