#include "AudioWriter.h"

#include "File.h"
#include "BinaryFile.h"
#include "AudioSample.h"

AudioWriter::AudioWriter()
{

}

void AudioWriter::SetPath(const std::string& path)
{
    mPath = path;
}

void AudioWriter::Write(const AudioSamplePtr& sample)
{
    if (mPath.empty())
    {
        return;
    }

    const auto sample_rate = sample->GetSampleRate();
    const auto num_channels = sample->GetNumChannels();
    const auto bytes_per_sample = sample->GetBitDepth() / 8;
    unsigned byte_rate = sample_rate*num_channels*bytes_per_sample;

    File outfile(mPath);
    outfile.SetAccessMode(File::AccessMode::Write);
    outfile.Open(true);
    auto handle = outfile.GetOutHandle();

    handle->write("RIFF", 4);
    auto data = sample->GetChannelData(0);
    const auto num_samples = data.size();
    unsigned content_size = 36 + bytes_per_sample* num_samples*num_channels;

    BinaryFile::Write<int>(handle, content_size);
    handle->write("WAVE", 4);

    /* write fmt  subchunk */
    handle->write("fmt ", 4);
    BinaryFile::Write<int>(handle, 16); // SubChunk1Size
    BinaryFile::Write<short>(handle, 1); // PCM Format
    BinaryFile::Write<short>(handle, num_channels);
    BinaryFile::Write<int>(handle, sample_rate);
    BinaryFile::Write<int>(handle, byte_rate);
    BinaryFile::Write<short>(handle, num_channels*bytes_per_sample); // block align
    BinaryFile::Write<short>(handle, 8*bytes_per_sample); // bits/sample

    /* write data subchunk */
    handle->write("data", 4);
    BinaryFile::Write<int>(handle, bytes_per_sample* num_samples*num_channels); // bits/sample

    handle->write(reinterpret_cast<const char*>(&data[0]), data.size()*sizeof(short));
    outfile.Close();
}
