#include <QApplication>

#include "SoundPlayer.h"

SoundPlayer::SoundPlayer(QWidget *container)
	: QWidget(container)
	, m_isLooping(false)
	, m_isPlaying(false)
	, m_source("")
{
	m_audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, container);
	m_mediaObject = new Phonon::MediaObject(container);
	Phonon::createPath(m_mediaObject, m_audioOutput);
	m_volumeSlider = new Phonon::VolumeSlider(container);
	m_volumeSlider->setAudioOutput(m_audioOutput);
	connect(m_audioOutput, SIGNAL(volumeChanged(qreal)), this, SIGNAL(volumeChanged(qreal)));
	connect(m_audioOutput, SIGNAL(mutedChanged(bool)), this, SLOT(mutedChanged(bool)));
	connect(m_mediaObject, SIGNAL(finished()), SLOT(finished()));
}

SoundPlayer::~SoundPlayer()
{
	stop();
	delete m_mediaObject;
	delete m_audioOutput;
}

void SoundPlayer::stop()
{
	m_isLooping = false;
	m_isPlaying = false;
	m_mediaObject->stop();
}

void SoundPlayer::setSource(const QString &source)
{
	bool wasPlaying = m_isPlaying, wasLooping = m_isLooping;
	stop();
	m_source = source;
	if (wasPlaying)
		play();
	else if (wasLooping)
		playLooping();
}

void SoundPlayer::play()
{
	m_mediaObject->setCurrentSource(Phonon::MediaSource(m_source));
	m_mediaObject->play();
	m_isPlaying = true;
}

void SoundPlayer::playLooping()
{
	m_isLooping = true;
	play();
}

void SoundPlayer::finished()
{
	if (m_isLooping)
		play();
	else
		m_isPlaying = false;
}

void SoundPlayer::mutedChanged( bool muted )
{
	emit volumeChanged( muted ? 0 : volume() );
}
