/*********************************************************\
		 __      __           __  __
		/ /     / / _____    / / / / ______   __     __
	   / /     / / /___  \  / / / / / ___  | / /    / /
	  / /_____/ / _____| / / / / / / /__/ / / /    / /
	 / ______  / / ___  / / / / / / _____/ / /    / /
	/ /     / / / /__/ / / / / / / |____  / |____/ /
   /_/     /_/ |______/ /_/ /_/  \_____/  \_____  /
										 ______/ /
			High Level Game Framework   /_______/

  ------------------------------------------------------

  Copyright (c) 2008 - Rodrigo Braz Monteiro.
  This file is subject to the terms of license.txt.

\*********************************************************/

#include "audio_sample.h"
#include "SDL_mixer.h"
#include "resource_locator.h"
#include "exception.h"

using namespace Halley;

AudioSample::AudioSample(String filename)
	: chunk(nullptr)
{
	auto data = ResourceLocator::get(filename);
	chunk = Mix_LoadWAV_RW(data->getRWOps(), 1);
	if (!chunk) {
		throw Exception("Error loading sample \""+filename+"\": "+Mix_GetError());
	}
}

AudioSample::~AudioSample()
{
	if (chunk) {
		Mix_FreeChunk(chunk);
	}
}

bool AudioSample::play(int channel, float pan, float volume)
{
	// Normalise volume
	volume = std::max(0.0f, std::min(volume, 1.0f)) * 255.0f;

	// Panning and volume
	float lPan = 1-abs(pan);
	float rPan = 1-abs(pan-1);
	Uint8 left = (Uint8) std::max(0.0f, std::min(lPan * volume, 255.0f));
	Uint8 right = (Uint8) std::max(0.0f, std::min(rPan * volume, 255.0f));
	
	// Check if there's anything to play
	if (left == 0 && right == 0) {
		// Nothing to play
		return false;
	} else {
		// Play
		Mix_SetPanning(channel, left, right);
		Mix_PlayChannel(channel, chunk, 0);
		return true;
	}
}
