/*
	Copyright (C) 2024-2025 Mark Tyler

	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 in the file COPYING.
*/

#include <mtdatawell_math.h>

#include "mtwasp.h"



mtWasp::Player::Player ()
{
	SDL_zero ( m_audiospec );

	m_audiospec.freq = MTWASP_AUDIOSPEC_HZ;
	m_audiospec.format = AUDIO_S16SYS;
	m_audiospec.channels = MTWASP_AUDIOSPEC_CHANNELS;
	m_audiospec.samples = MTWASP_AUDIOSPEC_SAMPLES;
	m_audiospec.callback = nullptr;

	set_audio_device ( MTWASP_AUDIO_DEVICE_DEFAULT );
}

int mtWasp::Player::init_audio_device ()
{
	if ( m_audio_device_ready )
	{
		// Device already initialized
		return 0;
	}

	if ( m_audio_player.open_device ( m_audio_device, m_audiospec ) )
	{
		std::cerr << "mtWasp::init_audio_device ERROR - Unable to "
			"open audio device.\n";
		return 1;
	}

	m_audio_device_ready = 1;

	return 0;
}

int mtWasp::Player::play_audio ( Sample const & sample )
{
	if ( init_audio_device () )
	{
		return 1;
	}

	size_t const samples = sample.wave_buf_samples();
	short const * buf = sample.wave_buf();

	m_audio_player.pause ();
	m_audio_player.queue_flush ();

	if ( m_audio_player.queue_data ( buf, samples ) )
	{
		std::cerr << "mtWasp::Project::play_wave_audio ERROR: "
			"Unable to queue data.\n";
		return 1;
	}

	if ( m_audio_player.resume () )
	{
		std::cerr << "mtWasp::Project::play_wave_audio ERROR: "
			"Unable to resume playing audio.\n";
		return 1;
	}

	return 0;
}

int mtWasp::Player::stop_audio ()
{
	return m_audio_player.pause ();
}

