#include "WavRecorder.h"
#include <cstdio>

WavRecorder::WavRecorder()
{
}

WavRecorder::~WavRecorder()
{
	stop();
}

bool WavRecorder::start (const File &destFile, double sampleRate, int numChannels)
{
	if (numChannels <= 0)
	{
		fprintf (stderr, "testhost: cannot record - plugin reports %d output channels\n", numChannels);
		return false;
	}

	destFile.deleteFile();
	ScopedPointer<FileOutputStream> stream (destFile.createOutputStream());

	if (stream == nullptr)
	{
		fprintf (stderr, "testhost: could not open '%s' for writing\n", destFile.getFullPathName().toRawUTF8());
		return false;
	}

	WavAudioFormat wavFormat;
	AudioFormatWriter *newWriter = wavFormat.createWriterFor (stream, sampleRate,
		(unsigned int) numChannels, 24, StringPairArray(), 0);

	if (newWriter == nullptr)
	{
		fprintf (stderr, "testhost: WavAudioFormat rejected the requested format (rate=%.0f, channels=%d)\n",
			sampleRate, numChannels);
		return false;
	}

	stream.release(); // now owned by newWriter
	writer = newWriter;
	return true;
}

void WavRecorder::write (const AudioSampleBuffer &buffer, int numSamples)
{
	if (writer != nullptr)
		writer->writeFromAudioSampleBuffer (buffer, 0, numSamples);
}

void WavRecorder::stop()
{
	writer = nullptr; // AudioFormatWriter's destructor flushes and finalises the file
}
