/*****************************************************************

Copyright (c) 2000-2001 the noatun authors. See file AUTHORS.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIAB\ILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kiconloader.h>
#include <klocale.h>
#include <qdragobject.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qtoolbutton.h>
#include <qtooltip.h>
#include <qwidget.h>
#include <qvbox.h>

#include "engine.h"
#include "kaboodle_part.h"

static QButton *createButton(const QIconSet &_iconset, const QString &_tip, QObject *_receiver, const char *_slot, QWidget *_parent)
{
	QToolButton *button = new QToolButton(_parent);
	button->setMaximumSize(50, 50);
	button->setIconSet(_iconset);
	QToolTip::add(button, _tip);
	QObject::connect(button, SIGNAL(clicked()), _receiver, _slot);
	button->show();
	return button;
}

KaboodlePart::KaboodlePart(QWidget *parent, const char *name, bool showButtons, bool viaBrowser)
	: KParts::ReadOnlyPart(parent, name)
	, extension(0)
	, videoEmbed(0)
	, playButton(0)
	, pauseButton(0)
	, stopButton(0)
{
	setInstance(KaboodleFactory::instance());

	player = new Player(this);

	box = new QVBox(parent);
	box->setSpacing(KDialog::spacingHint());
	box->setMargin(0);

	QWidget *sliderBox = new QWidget(box);
	sliderBox->setFocusPolicy(QWidget::ClickFocus);
	sliderBox->setAcceptDrops(true);

	QHBoxLayout *layout = new QHBoxLayout(sliderBox);
	layout->setSpacing(KDialog::spacingHint());
	layout->setMargin(0);
	layout->setAutoAdd(true);

	KParts::Part::setWidget(box);

	if(viaBrowser)
	{
		extension = new KaboodleBrowserExtension(this);
		extension->setURLDropHandlingEnabled(true);

		connect(player->engine(), SIGNAL(x11WindowId(int)), SLOT(embedVideo(int)));
	}

	if(showButtons)
	{
		playButton = createButton(BarIconSet("1rightarrow"), i18n("Play"), player, SLOT(play()), sliderBox);
		pauseButton = createButton(BarIconSet("player_pause"), i18n("Pause"), player, SLOT(pause()), sliderBox);
		stopButton = createButton(BarIconSet("player_stop"), i18n("Stop"), this, SLOT(stop()), sliderBox);
	}

	slider = new L33tSlider(0, 1000, 10, 0, L33tSlider::Horizontal, sliderBox);
	slider->setTickmarks(QSlider::NoMarks);
	slider->show();

	elapsedLabel = new QLabel(sliderBox);
	QFont labelFont = elapsedLabel->font();
	labelFont.setPointSize(24);
	labelFont.setBold(true);
	QFontMetrics labelFontMetrics = labelFont;
	elapsedLabel->setFont(labelFont);
	elapsedLabel->setAlignment(AlignCenter | AlignVCenter | ExpandTabs);
	elapsedLabel->setText("00:00");
	elapsedLabel->setFixedHeight(labelFontMetrics.height());
	elapsedLabel->setMinimumWidth(elapsedLabel->sizeHint().width());

	playAction = new KAction(i18n("&Play"), 0, player, SLOT(play()), actionCollection(), "play");
	pauseAction = new KAction(i18n("&Pause"), 0, player, SLOT(pause()), actionCollection(), "pause");
	stopAction = new KAction(i18n("&Stop"), 0, this, SLOT(stop()), actionCollection(), "stop");
	loopAction = new KToggleAction(i18n("&Looping"), 0, this, SLOT(loop()), actionCollection(), "loop");
	
	setXMLFile("kaboodlepartui.rc");
	setLooping(false);

	connect(player, SIGNAL(playing()), this, SLOT(playerPlaying()));
	connect(player, SIGNAL(stopped()), this, SLOT(playerStopped()));
	connect(player, SIGNAL(paused()), this, SLOT(playerPaused()));
	connect(player, SIGNAL(finished()), this, SLOT(playerFinished()));
	
	player->handleButtons();

	connect(player, SIGNAL(timeout()), this, SLOT(playerTimeout()));
	connect(player, SIGNAL(loopingChange(bool)), this, SLOT(loopingChange(bool)));
	connect(player, SIGNAL(opened(const KURL &)), this, SLOT(playerOpened(const KURL &)));

	connect(slider, SIGNAL(userChanged(int)), this, SLOT(skipToWrapper(int)));
	connect(this, SIGNAL(skipTo(unsigned long)), player, SLOT(skipTo(unsigned long)));
	connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(sliderMoved(int)));
	slider->setEnabled(false);

	loopingChange(false);
	updateTitle();
	handleLengthString("00:00/00:00");
	
	lastEmitted = KURL();
}

KaboodlePart::~KaboodlePart()
{
	disconnect(player, SIGNAL(playing()), this, SLOT(playerPlaying()));
	disconnect(player, SIGNAL(stopped()), this, SLOT(playerStopped()));
	disconnect(player, SIGNAL(paused()), this, SLOT(playerPaused()));

	delete player;
}

void KaboodlePart::embedVideo(int wid)
{
	videoEmbed = new VideoEmbed(box);
	videoEmbed->embed(wid);
	videoEmbed->show();
}

void KaboodlePart::openFile(const KURL &url)
{
	player->openFile(url);
}

void KaboodlePart::playerPlaying()
{
	slider->setEnabled(true);
	stopAction->setEnabled(true);
	playAction->setEnabled(false);
	pauseAction->setEnabled(true);
	if(stopButton)
	{
		stopButton->setEnabled(true);
		playButton->setEnabled(false);
		pauseButton->setEnabled(true);
	}
	updateTitle();
}

void KaboodlePart::playerStopped()
{
	slider->setEnabled(false);
	if(player->current().isEmpty())
		return;

	updateTitle();

	slider->setValue(0);
	handleLengthString("00:00/00:00");
	stopAction->setEnabled(false);
	playAction->setEnabled(true);
	pauseAction->setEnabled(false);
	if(stopButton)
	{
		stopButton->setEnabled(false);
		playButton->setEnabled(true);
		pauseButton->setEnabled(false);
	}
}

void KaboodlePart::playerPaused()
{
	slider->setEnabled(true);
	stopAction->setEnabled(true);
	playAction->setEnabled(true);
	pauseAction->setEnabled(false);
	if(stopButton)
	{
		stopButton->setEnabled(true);
		playButton->setEnabled(true);
		pauseButton->setEnabled(false);
	}

	updateTitle();
}

void KaboodlePart::playerFinished()
{
	if(checkQuit()) kapp->quit();
}

void KaboodlePart::loopingChange(bool b)
{
	loopAction->setChecked(b);
}

void KaboodlePart::playerTimeout()
{
	if(player->current().isEmpty())
		return;

	if(slider->currentlyPressed())
		return;

	updateTicks();
	slider->setValue((int)(player->getTime() / 1000));

	handleLengthString( player->lengthString() );
}

void KaboodlePart::updateTicks(void)
{
	if(player->getLength())
	{
		int range = (int)(player->getLength() / 1000);
		slider->setRange(0, range);
	}
	else
	{
		slider->setRange(0, 1);
	}
}

void KaboodlePart::playerOpened(const KURL &)
{
	if(autoPlay())
		player->play();
}

void KaboodlePart::sliderMoved(int seconds)
{
	if(!player->current().isEmpty())
	handleLengthString(player->lengthString(seconds*1000));
}

void KaboodlePart::skipToWrapper(int second)
{
	emit skipTo((unsigned long)(second*1000));
}

void KaboodlePart::stop()
{
	player->stop();

	delete videoEmbed;
	videoEmbed = 0;
}

void KaboodlePart::loop()
{
	setLooping(loopAction->isChecked());
}

void KaboodlePart::setLooping(bool value)
{
	player->setLooping(value);
}

void KaboodlePart::updateTitle()
{
	if(!player->current().isEmpty() && (lastEmitted != player->current()))
	{
		lastEmitted = player->current();
		emit setWindowCaption(player->current().prettyURL());
	}
}

void KaboodlePart::handleLengthString(const QString &text)
{
	if(elapsedLabel)
		elapsedLabel->setText(text.left(5));

	if(extension)
		emit setStatusBarText(i18n("Playing %1 - %2")
		       .arg(player->current().prettyURL())
			  .arg((player->lengthString()).left(5)));
}	

bool KaboodlePart::openFile()
{
	openFile(m_file);
	return true;
}

bool KaboodlePart::autoPlay()
{
	KConfig &config = *KGlobal::config();
	config.setGroup("core");
	return config.readBoolEntry("autoPlay", true);
}

void KaboodlePart::setAutoPlay(bool b)
{
	KConfig &config = *KGlobal::config();
	config.setGroup("core");
	config.writeEntry("autoPlay", b);
	config.sync();
}

bool KaboodlePart::quitAfterPlaying()
{
	KConfig &config = *KGlobal::config();
	config.setGroup("core");
	return config.readBoolEntry("quitAfterPlaying", true);
}

void KaboodlePart::setQuitAfterPlaying(bool b)
{
	KConfig &config = *KGlobal::config();
	config.setGroup("core");
	config.writeEntry("quitAfterPlaying", b);
	config.sync();
}

bool KaboodlePart::checkQuit()
{
	return (extension == 0) && quitAfterPlaying();
}

#include "kaboodle_part.moc"
