#include "redirectstream.h"

using namespace Halley;

RedirectStream::RedirectStream(std::ostream& stream, bool _exclusive)
	: orgstream(stream)
	, exclusive(_exclusive)
{
	// Swap the the old buffer in ostream with this buffer.
	orgbuf = orgstream.rdbuf(this);

	// Create a new ostream that we set the old buffer in
	newstream = shared_ptr<std::ostream>(new std::ostream(orgbuf));
}

RedirectStream::~RedirectStream(){
	//Restore old buffer
	orgstream.rdbuf(orgbuf);
}

std::streamsize RedirectStream::xsputn(const char *msg, std::streamsize count){
	onText(msg, count);

	// Output to original stream
	if (!exclusive) {
		newstream->write(msg, count);
	}

	return count;
}

int RedirectStream::overflow(int c)
{
	char tmp = c;
	xsputn(&tmp, 1);

	if (!exclusive) {
		newstream->flush();
	}
	onFlush();

	return 0;
}

RedirectStreamToStream::RedirectStreamToStream(std::ostream& source, shared_ptr<std::ostream> _dst, bool exclusive)
	: RedirectStream(source, exclusive)
	, dst(_dst)
{
}

RedirectStreamToStream::~RedirectStreamToStream()
{
}

void RedirectStreamToStream::onText(const char *msg, std::streamsize count)
{
	dst->write(msg, count);
}

void RedirectStreamToStream::onFlush()
{
	dst->flush();
}

