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

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 <tdeapplication.h>
#include <tdecmdlineargs.h>
#include <tdeconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <kvideowidget.h>
#include <tqdragobject.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqtoolbutton.h>
#include <tqtooltip.h>
#include <tqwidget.h>
#include <tqvbox.h>

#include "view.h"
#include "player.h"

namespace
{
TQButton *createButton(const TQIconSet &_iconset, const TQString &_tip, TQObject *_receiver, const char *_slot, TQWidget *_parent)
{
	TQToolButton *button = new TQToolButton(_parent);
	button->setMaximumSize(50, 50);
	button->setIconSet(_iconset);
	TQToolTip::add(button, _tip);
	TQObject::connect(button, TQ_SIGNAL(clicked()), _receiver, _slot);
	button->show();
	return button;
}
}

Kaboodle::View::View(TQWidget *parent, const char *name, Player *p)
	: KMediaPlayer::View(parent, name)
	, state((KMediaPlayer::Player::State)p->state())
	, autoPlay(false)
	, quitAfterPlaying(false)
	, player(p)
	, firstVideo(false)
	, lastWidth(0)
{
	(new TQHBoxLayout(this))->setAutoAdd(true);
	TQVBox *box = new TQVBox(this);
	box->setSpacing(KDialog::spacingHint());
	box->setMargin(0);

	video = new KVideoWidget(player, box);
	video->actionCollection()->readShortcutSettings();
	setVideoWidget(video);
	connect(video, TQ_SIGNAL(adaptSize(int, int)), this, TQ_SLOT(calculateSize(int, int)));
	connect(video, TQ_SIGNAL(mouseButtonPressed(int, const TQPoint&, int)), this, TQ_SLOT(slotButtonPressed(int, const TQPoint &, int) ) ) ;
	connect(video, TQ_SIGNAL(mouseButtonDoubleClick(const TQPoint&, int)), this, TQ_SLOT(slotDblClick(const TQPoint &, int) ) ) ;

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

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

	playButton = createButton(BarIconSet("1rightarrow"), i18n("Play"), player, TQ_SLOT(play()), sliderBox);
	pauseButton = createButton(BarIconSet("media-playback-pause"), i18n("Pause"), player, TQ_SLOT(pause()), sliderBox);
	stopButton = createButton(BarIconSet("media-playback-stop"), i18n("Stop"), player, TQ_SLOT(stop()), sliderBox);

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

	elapsedLabel = new TQLabel(sliderBox);
	TQFont labelFont = elapsedLabel->font();
	labelFont.setPointSize(24);
	labelFont.setBold(true);
	TQFontMetrics labelFontMetrics(labelFont);
	elapsedLabel->setFont(labelFont);
	elapsedLabel->setAlignment(AlignCenter | AlignVCenter | ExpandTabs);
	elapsedLabel->setFixedHeight(labelFontMetrics.height());
	elapsedLabel->setMinimumWidth(labelFontMetrics.width("00:00"));

	connect(player, TQ_SIGNAL(stateChanged(int)), this, TQ_SLOT(stateChanged(int)));
	connect(player, TQ_SIGNAL(completed()), this, TQ_SLOT(playerFinished()));
	connect(player, TQ_SIGNAL(timeout()), this, TQ_SLOT(playerTimeout()));

	connect(slider, TQ_SIGNAL(userChanged(int)), this, TQ_SLOT(skipToWrapper(int)));
	connect(slider, TQ_SIGNAL(sliderMoved(int)), this, TQ_SLOT(sliderMoved(int)));
	slider->setEnabled(false);

	connect(this, TQ_SIGNAL(buttonsChanged(int)), this, TQ_SLOT(updateButtons(int)));
	updateButtons(buttons());

	updateLabel("--:--/--:--");

	video->setMinimumHeight(0);
}

Kaboodle::View::~View(void)
{
	embed(Arts::PlayObject::null());
}

void Kaboodle::View::stateChanged(int s)
{
	KMediaPlayer::Player::State oldState = state;
	state = (KMediaPlayer::Player::State)s;

	switch(state)
	{
	case KMediaPlayer::Player::Play:
		stopButton->setEnabled(true);
		playButton->setEnabled(false);
		pauseButton->setEnabled(true);
		break;
	
	case KMediaPlayer::Player::Empty:
		slider->setEnabled(false);
		slider->setValue(0);
		updateLabel("--:--");
		stopButton->setEnabled(false);
		playButton->setEnabled(false);
		pauseButton->setEnabled(false);
		break;

	case KMediaPlayer::Player::Stop:
		slider->setEnabled(false);
		slider->setValue(0);
		updateLabel("00:00");
		stopButton->setEnabled(false);
		playButton->setEnabled(true);
		pauseButton->setEnabled(false);

		// loaded
		if(oldState == KMediaPlayer::Player::Empty)
		{
			firstVideo = true;
			if(autoPlay) player->play();
		}

		break;
	
	case KMediaPlayer::Player::Pause:
		slider->setEnabled(player->isSeekable());
		stopButton->setEnabled(true);
		playButton->setEnabled(true);
		pauseButton->setEnabled(false);
		break;
	}
}

void Kaboodle::View::playerFinished()
{
	if(quitAfterPlaying) kapp->quit();
}

void Kaboodle::View::playerTimeout()
{
	if(player->currentURL().isEmpty())
		return;

	if(slider->currentlyPressed())
		return;

	updateTicks();

	if(firstVideo)
	{
		if(!lastWidth)
		{
			video->setNormalSize();
		}
		else
		{
			firstVideo = false;
			lastWidth = 0;
		}
	}

	if(player->isSeekable())
	{
		slider->setEnabled(true);
		slider->setValue((int)(player->position() / 1000));
	}

	updateLabel( player->positionString() );
}

void Kaboodle::View::updateTicks(void)
{
	if(player->hasLength())
	{
		int range = (int)(player->length() / 1000);
		slider->setRange(0, range);
	}
	else
	{
		slider->setRange(0, 1);
	}
}

void Kaboodle::View::sliderMoved(int seconds)
{
	if(!player->currentURL().isEmpty())
	updateLabel(Player::timeString(seconds*1000));
}

void Kaboodle::View::skipToWrapper(int second)
{
	player->seek((unsigned long)(second*1000));
}

void Kaboodle::View::updateLabel(const TQString &text)
{
	if(elapsedLabel)
		elapsedLabel->setText(text.left(5));
}

void Kaboodle::View::calculateSize(int newWidth, int newHeight)
{
	lastWidth = newWidth;
	int extraWidth = width() - video->width();
	int extraHeight = height() - video->height();
	newWidth += extraWidth;
	newHeight += extraHeight;
	emit adaptSize(newWidth, newHeight);
}

bool Kaboodle::View::isAutoPlay()
{
	return autoPlay;
}

void Kaboodle::View::setAutoPlay(bool b)
{
	autoPlay = b;
}

bool Kaboodle::View::isQuitAfterPlaying()
{
	return quitAfterPlaying;
}

void Kaboodle::View::setQuitAfterPlaying(bool b)
{
	quitAfterPlaying = b;
}

void Kaboodle::View::embed(Arts::PlayObject object)
{
	video->embed(Arts::DynamicCast(object));
}

void Kaboodle::View::updateButtons(int b)
{
	if(b & Play)
		playButton->show();
	else
		playButton->hide();

	if(b & Pause)
		pauseButton->show();
	else
		pauseButton->hide();

	if(b & Stop)
		stopButton->show();
	else
		stopButton->hide();

	if(b & Seeker)
	{
		slider->show();
		elapsedLabel->show();
	}
	else
	{
		slider->hide();
		elapsedLabel->hide();
	}

}

void Kaboodle::View::slotButtonPressed(int /*type*/, const TQPoint &, int /* state */)
{
	if((KMediaPlayer::Player::State)player->state() == KMediaPlayer::Player::Pause )
		player->play();
	else player->pause();
}

void Kaboodle::View::slotDblClick( const TQPoint &, int /* state */)
{
	if ( video->isFullscreen() )
		video->setWindowed();
	else  video->setFullscreen(); 
	
	player->play(); // play() is called because the video is stopped when double-clicking ( slotButtonPressed is called )
}

#include "view.moc"
