/*
 * SoundPlayer.h
 *
 *  Created on: 24.01.2012
 *      Author: stefan.detter
 */

#ifndef SOUNDPLAYER_H_
#define SOUNDPLAYER_H_

#include "Sound.h"

#if	USE_SOUND

#include <QThread>
#include <QMap>
#include <QFile>
#include <QSemaphore>
#include <QMutex>
#include <QWaitCondition>
#include <QDateTime>
#include <QSoundEffect>

#include <QAudioFormat>
#include <QAudioOutput>

#include <QrfeTraceModule>

#include "SoundFormat.h"

class SoundPlayerWorker;
class SoundPlayerPrivate;

typedef struct {
	QString 		fileName;
	QAudioFormat 	format;
	int 			offset;
} SOUND_INFO;

class SoundPlayer : public QObject /*, QrfeTraceModule */
{
	Q_OBJECT

public:
	SoundPlayer(QObject* parent = 0);
	virtual ~SoundPlayer();

	bool setFiles ( QStringList fileList );
	bool setParallelCount (uint count);

public slots:
	void play(int index);


private:
	QList<SOUND_INFO> 				m_soundInfos;

	uint 							m_parallelCount;
	QList<SoundPlayerWorker*>		m_threads;

	QMutex                          m_runningMutex;
	int								m_running;

    QMutex                          m_mutex;
    QList<int>                      m_index;
	QWaitCondition					m_waitCondition;
	//QMutex                          m_waitMutex;

	friend class SoundPlayerWorker;
	friend class SoundPlayerPrivate;
};

class SoundPlayerWorker : public QThread
{
	Q_OBJECT

public:
	SoundPlayerWorker(SoundPlayer* parent);
	virtual ~SoundPlayerWorker();

	void exitThread();

protected:
	virtual void run();

private:
	SoundPlayer*					m_parent;

	QMutex							m_waitMutex;

	bool                            m_running;
	bool                            m_exitThread;

    static QMutex                   m_lastPlayedMutex;
    static QTime                    m_lastPlayed;
};


class SoundPlayerPrivate : public QObject /*, QrfeTraceModule */
{
    Q_OBJECT

public:
    SoundPlayerPrivate(SoundPlayer* parent);
    ~SoundPlayerPrivate();

public slots:
    void play(int index);
//    void _q_stateChanged ( QAudio::State state );

private slots:
	void playingChanged();

signals:
	void finished();

private:
    SoundPlayer*					m_parent;
    QMap<QAudioOutput*, QFile*> 	m_audio;
    QSoundEffect                    m_sound;
	bool							m_playing;
};

#endif

#endif /* SOUNDPLAYER_H_ */
