//
//  Wumbo-BGM.cpp
//  Wumbo
//
//  Created by Wade McGillis on 12/13/13.
//  Copyright (c) 2013 Wade McGillis. All rights reserved.
//

#include "Wumbo-BGM.h"


#if PLATFORM_IOS
#include <fstream>
#include <sstream>
#include <UIKit/UIKit.h>
#include <AudioToolbox/AudioServices.h>
#include <Foundation/Foundation.h>
#include "Wumbo-Functions.h"
#endif
namespace Wumbo
{
	BGM::BGM()
	{
		volume = 100;
	}

	BGM::~BGM()
	{
#if PLATFORM_IOS
		//[sound dealloc]; ARC dumb
#endif
	}


#if PLATFORM_IOS
	AVAudioPlayer *BGM::getSound()
	{
		return sound;
	}
#endif

#if PLATFORM_APPLE
void BGM::load(NSString *fname)
#else
void BGM::load(std::string fname)
#endif
{
	//printf("BGM:load %s\n",[fname UTF8String]);
#if PLATFORM_IOS
	NSURL *filePath = [NSURL fileURLWithPath:fname isDirectory:NO];
    //NSError *err = [[NSError alloc] init];
    sound = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:nil];
    [sound prepareToPlay];
	//[err dealloc];
#elif PLATFORM_PC
#if PLATFORM_WINDOWS
	if (!buffer.loadFromFile(fname))
	{
		printf("Could not find %s",fname.c_str());
#elif PLATFORM_OSX
		if (!buffer.loadFromFile([fname UTF8String]))
	{
		printf("Could not find %s",[fname UTF8String]);
#endif
		return;
	}
		sound = sf::Sound(buffer);
#endif
	}
	
	void BGM::loop()
	{
#if PLATFORM_IOS
		if (sound.playing == NO)//(s.isPlaying == NO)
		{
			sound.volume = (float)volume/100.f;
			sound.numberOfLoops = -1;
			[sound play];
		}
#elif PLATFORM_PC
		//printf("PLAY THE SOUND!");
		if (sound.getStatus() != sf::Sound::Playing)
		{
			sound.setLoop(true);
			sound.setVolume(volume);
			sound.play();
        }
#endif
	}
	
	void BGM::play()
	{
#if PLATFORM_IOS
		if (sound.playing == NO)//(s.isPlaying == NO)
		{
			sound.volume = (float)volume/100.f;
			sound.numberOfLoops = 0;
			[sound play];
		}
#elif PLATFORM_PC
		//printf("PLAY THE SOUND!");
		if (sound.getStatus() != sf::Sound::Playing)
		{
			sound.setLoop(false);
			sound.setVolume(volume);
			sound.play();
		}
#endif
	}
	
	void BGM::stop()
	{
#if PLATFORM_IOS
		[sound stop];
#elif PLATFORM_PC
		sound.stop();
#endif
	}
    
	bool BGM::isPlaying()
	{
#if PLATFORM_IOS
		return sound.isPlaying;
#elif PLATFORM_PC
		return (sound.getStatus() == sf::Sound::Playing);
#endif
	}
	
	void BGM::pause()
	{
#if PLATFORM_IOS
		[sound pause];
#elif PLATFORM_PC
		sound.pause();
#endif
	}
	
	int BGM::length()
	{
#if PLATFORM_IOS
		return sound.duration*1000;
#elif PLATFORM_PC
		printf("Sound duration: %i\n",buffer.getDuration().asMilliseconds());
		return buffer.getDuration().asMilliseconds();
#endif
	}
	
	void BGM::setVolume(int vol)
	{
		volume = vol;
	}
};