/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/audio/source.hpp"

#include <al.h>
#include <alc.h>

#include "game/audio/buffer.hpp"
#include "common/logger.hpp"

using namespace polygun::audio;

AudioSource::AudioSource() :
	m_buffer(),
	m_source_id(0),
	m_valid(false)
{
	alGenSources(1, &m_source_id);
	ALCenum error = alGetError();
	if(error!=AL_NO_ERROR) {
		LOG_ERROR("Failed to create OpenAL source (OpenAL error: %d)", error);
		return;
	}
	m_valid = true;
}

AudioSource::AudioSource(const std::shared_ptr<AudioBuffer>& buffer) :
	m_buffer(),
	m_source_id(0),
	m_valid(false)
{
	alGenSources(1, &m_source_id);
	ALCenum error = alGetError();
	if(error!=AL_NO_ERROR) {
		LOG_ERROR("Failed to create OpenAL source (OpenAL error: %d)", error);
		return;
	}
	m_valid = true;
	set_buffer(buffer);
}

AudioSource::~AudioSource() {
	if(m_valid)
		alDeleteSources(1, &m_source_id);
}

void AudioSource::set_buffer(const std::shared_ptr<AudioBuffer>& buffer) {
	if(m_valid) {
		m_buffer = buffer;
		alSourcei(m_source_id, AL_BUFFER, m_buffer->get_buffer_id());
	}
}

void AudioSource::set_gain(float gain) {
	if(m_valid)
		alSourcef(m_source_id, AL_GAIN, gain);
}

void AudioSource::set_position(const glm::vec3& pos) {
	if(m_valid)
		alSource3f(m_source_id, AL_POSITION, pos.x, pos.y, pos.z);
}

void AudioSource::set_velocity(const glm::vec3& vel) {
	if(m_valid)
		alSource3f(m_source_id, AL_VELOCITY, vel.x, vel.y, vel.z);
}

void AudioSource::play(bool looping) {
	alSourcei(m_source_id, AL_LOOPING, looping);
	alSourcePlay(m_source_id);
}

void AudioSource::stop() {
	alSourceStop(m_source_id);
}

void AudioSource::pause() {
	alSourcePause(m_source_id);
}

bool AudioSource::is_playing() const {
	int source_state;
	alGetSourcei(m_source_id, AL_SOURCE_STATE, &source_state);
	return source_state==AL_PLAYING;
}
