#include "example.h"

#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QAction>
#include <QtGui/QToolBar>
#include <phonon/mediaobject.h>
#include <phonon/audiooutput.h>
#include <phonon/videowidget.h>
#include <QFileDialog>
#include <QDockWidget>
#include <QListView>
#include "playlistmodel.h"
#include "controlsview.h"

Example::Example()
{
	QToolBar* tools=addToolBar("Controls");
	tools->addAction("Open", this, SLOT(selectFile()));
	tools->addAction("Play/Pause", this, SLOT(play()));
	tools->addAction("Stop", this, SLOT(stop()));
	tools->addAction("Next", this, SLOT(finished()));
	
	mediaObject = new Phonon::MediaObject(this);
	
	Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
	Phonon::Path path = Phonon::createPath(mediaObject, audioOutput);
	
	Phonon::VideoWidget *vwidget = new Phonon::VideoWidget(this);
	Phonon::createPath(mediaObject, vwidget);
	
	connect(mediaObject, SIGNAL(finished()), SLOT(finished()));
	
	//Playlist dock
	QDockWidget* playlistDock=new QDockWidget("Playlist", this);
	QListView* playlistView=new QListView(playlistDock);
	playlist=new PlaylistModel(playlistView);
	playlistView->setModel(playlist);
	
	playlistDock->setWidget(playlistView);
	addDockWidget(Qt::RightDockWidgetArea, playlistDock);
	
	setCentralWidget(vwidget);
	
	//Controls dock
	QDockWidget* controlsDock=new QDockWidget("Controls", this);
	controls = new ControlsView(controlsDock);
	controlsDock->setWidget(controls);
	addDockWidget(Qt::BottomDockWidgetArea, controlsDock);
	
	connect(controls, SIGNAL(progressChanged(qreal)), SLOT(timeChanged(qreal)));
	
	setCentralWidget(vwidget);
}

Example::~Example()
{}

QSize Example::sizeHint() const
{
	return QSize(400,300);
}

void Example::selectFile()
{
	QString file=QFileDialog::getOpenFileName(this, "Open a file to reproduce", QString(), QString("Media (*.mp3 *.avi)"));
	bool empty=playlist->rowCount()==0;
	playlist->addFile(file);
	if(empty && mediaObject->state()!=Phonon::PlayingState)
		playNext();
}

void Example::playNext()
{
	mediaObject->setCurrentSource(playlist->next());
	mediaObject->play();
}

void Example::play()
{
	if(mediaObject->state()==Phonon::PlayingState)
		mediaObject->pause();
	else
		mediaObject->play();
}

void Example::stop()
{
	mediaObject->stop();
}

void Example::finished()
{
	playNext();
	controls->setCurrent(0);
}

void Example::timeChanged(qreal fraction)
{
	qint64 total=mediaObject->totalTime();
	mediaObject->seek(qint64(total*fraction));
}

#include "example.moc"
