// userinterface.cpp
//
// Copyright (C) 2001 Neil Stevens <neil@qualityassistant.com>
// Copyright (C) 1999 Charles Samuels <charles@kde.org>
//
// 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
// THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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.
//
// Except as contained in this notice, the name(s) of the author(s) shall not be
// used in advertising or otherwise to promote the sale, use or other dealings
// in this Software without prior written authorization from the author(s).

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <noatun/effects.h>
#include <noatun/app.h>
#include <noatun/controls.h>
#include <noatun/pref.h>
#include <noatun/player.h>

#include "userinterface.h"

#include <kbuttonbox.h>
#include <tdeconfig.h>
#include <tdefiledialog.h>
#include <tdeglobal.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <tdemenubar.h>
#include <tdemessagebox.h>
#include <kpixmapeffect.h>
#include <tdepopupmenu.h>
#include <kstatusbar.h>
#include <kstdaction.h>
#include <twin.h>
#include <kurldrag.h>

#include <tqbitmap.h>
#include <tqdragobject.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqobjectlist.h>
#include <tqobjectdict.h>
#include <tqpushbutton.h>
#include <tqtooltip.h>
#include <tqvbox.h>

Excellent::Excellent()
	: TDEMainWindow(0, "NoatunExcellent")
	, UserInterface()
{
	setAcceptDrops(true);

	KStdAction::quit(TQT_TQOBJECT(napp), TQT_SLOT(quit()), actionCollection());
	KStdAction::open(TQT_TQOBJECT(napp), TQT_SLOT(fileOpen()), actionCollection());
	setStandardToolBarMenuEnabled(true);

	menubarAction = KStdAction::showMenubar(TQT_TQOBJECT(this), TQT_SLOT(showMenubar()), actionCollection());
	KStdAction::preferences(TQT_TQOBJECT(napp), TQT_SLOT(preferences()), actionCollection());

	// buttons
	NoatunStdAction::back(actionCollection(), "back");
	NoatunStdAction::stop(actionCollection(), "stop");
	NoatunStdAction::play(actionCollection(), "play");
	NoatunStdAction::pause(actionCollection(), "pause");
	NoatunStdAction::forward(actionCollection(), "forward");
	NoatunStdAction::playlist(actionCollection(), "show_playlist");

	volumeAction = new TDEToggleAction(i18n("Show &Volume Control"), 0, TQT_TQOBJECT(this), TQT_SLOT(showVolumeControl()), actionCollection(), "show_volumecontrol");
	volumeAction->setCheckedState(i18n("Hide &Volume Control"));
	NoatunStdAction::effects(actionCollection(), "effects");
	NoatunStdAction::equalizer(actionCollection(), "equalizer");

	NoatunStdAction::loop(actionCollection(), "loop_style");

	createGUI("excellentui.rc");

	napp->pluginActionMenu()->plug(menuBar(),3);
	toolBar("mainToolBar")->hide();

	// Who needs TQt Designer?
	mainFrame = new TQHBox(this);
	mainFrame->setSpacing(KDialog::spacingHint());
	mainFrame->setMargin(0);
	slider = new L33tSlider(0, 1000, 10, 0, Qt::Horizontal, mainFrame);
	slider->setTickmarks(TQSlider::NoMarks);

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

	// Doing this makes the slider the same heigh as the font. This is just plain wrong...
	//slider->setFixedHeight(labelFontMetrics.height());

	setCentralWidget(mainFrame);

	total = new TQLabel(statusBar());
	labelFont = total->font();
	labelFont.setBold(true);
	total->setFont(labelFont);
	total->setAlignment(AlignCenter | AlignVCenter | ExpandTabs);
	total->setText("--:--");
	total->setMinimumWidth(total->sizeHint().width());
	total->setText("");

	statusBar()->addWidget(total, 0, true);
	statusBar()->show();

	connect( napp, TQT_SIGNAL(hideYourself()), this, TQT_SLOT(hide()) );
	connect( napp, TQT_SIGNAL(showYourself()), this, TQT_SLOT(show()) );

	connect(napp->player(), TQT_SIGNAL(playing()), this, TQT_SLOT(slotPlaying()));
	connect(napp->player(), TQT_SIGNAL(stopped()), this, TQT_SLOT(slotStopped()));
	connect(napp->player(), TQT_SIGNAL(paused()), this, TQT_SLOT(slotPaused()));
	napp->player()->handleButtons();

	connect(napp->player(), TQT_SIGNAL(timeout()), this, TQT_SLOT(slotTimeout()));
	connect(napp->player(), TQT_SIGNAL(loopTypeChange(int)), this, TQT_SLOT(slotLoopTypeChanged(int)));

	/* This skipToWrapper is needed to pass milliseconds to Player() as everybody
	 * below the GUI is based on milliseconds instead of some unprecise thingy
	 * like seconds or mille */
	connect(slider, TQT_SIGNAL(userChanged(int)), this, TQT_SLOT(skipToWrapper(int)));
	connect(this, TQT_SIGNAL(skipTo(int)), napp->player(), TQT_SLOT(skipTo(int)));

	connect(slider, TQT_SIGNAL(sliderMoved(int)), TQT_SLOT(sliderMoved(int)));

	setCaption("Noatun");
	setIcon(SmallIcon("noatun"));
	//slotLoopTypeChanged(Player::None);
	changeStatusbar();
	handleLengthString("--:--/--:--");

	setMinimumWidth(250);
	resize(300, 75);

	TDEConfig &config = *TDEGlobal::config();

	toolBar("main")->applySettings(&config, "Excellent main");

	config.setGroup("excellent");

	volumeSlider = 0;
	volumeAction->setChecked( config.readBoolEntry("volumeShown", false) );
	showVolumeControl();

	menubarAction->setChecked( config.readBoolEntry("menuShown", true) );
	showMenubar();

	applyMainWindowSettings(&config, "excellent");

	switch((NET::MappingState)config.readNumEntry("mappingState", (int)NET::Visible))
	{
	case NET::Visible:
		showNormal();
		break;
	case NET::Withdrawn:
		if (napp->libraryLoader()->isLoaded("systray.plugin"))
			hide();
		break;
	case NET::Iconic:
		showMinimized();
		break;
	}

	for (TQPtrListIterator<TQObject> i(childrenListObject()); i.current(); ++i)
		(*i)->installEventFilter(this);
}

Excellent::~Excellent()
{
	TDEConfig &config = *TDEGlobal::config();
	saveMainWindowSettings(&config, "excellent");
	toolBar("main")->saveSettings(&config, "Excellent main");
	config.setGroup("excellent");
	config.writeEntry("volumeShown", volumeAction->isChecked());
	config.writeEntry("menuShown", menubarAction->isChecked());
	config.writeEntry("width", width());
	config.writeEntry("height", height());
	config.sync();
}

void Excellent::showEvent(TQShowEvent *e)
{
	TDEConfig *config = TDEGlobal::config();
	config->setGroup("excellent");
	config->writeEntry("mappingState", NET::Visible);
	config->sync();

	TDEMainWindow::showEvent(e);
}

void Excellent::hideEvent(TQHideEvent *e)
{
	TDEConfig *config = TDEGlobal::config();
	config->setGroup("excellent");
	config->writeEntry("mappingState", NET::Withdrawn);
	config->sync();

	TDEMainWindow::hideEvent(e);
}

void Excellent::closeEvent(TQCloseEvent *)
{
	unload();
}

void Excellent::dragEnterEvent(TQDragEnterEvent *event)
{
	// accept uri drops only
	event->accept(KURLDrag::canDecode(event));
}

void Excellent::dropEvent(TQDropEvent *event)
{
	KURL::List uri;
	if (KURLDrag::decode(event, uri))
	{
		for (KURL::List::Iterator i = uri.begin(); i != uri.end(); ++i)
			napp->player()->openFile(*i, false);
	}
}

bool Excellent::eventFilter(TQObject *o, TQEvent *e)
{
	if (e->type() == TQEvent::Wheel)
	{
		wheelEvent(TQT_TQWHEELEVENT(e));
		return true;
	}
	return TQWidget::eventFilter(o, e);
}

void Excellent::wheelEvent(TQWheelEvent *e)
{
	int delta=e->delta();
	napp->player()->setVolume(napp->player()->volume() + delta/120*2);
}

void Excellent::slotPlaying()
{
	slider->setEnabled(true);
	changeStatusbar();
}

void Excellent::slotStopped()
{
	slider->setEnabled(false);
	if(!napp->player()->current()) return;
	changeStatusbar();
	slider->setValue(0);
	handleLengthString("--:--/--:--");
}

void Excellent::slotPaused()
{
	slider->setEnabled(true);
	changeStatusbar();
}

void Excellent::slotTimeout()
{
	if(volumeSlider) volumeSlider->setValue(100 - napp->player()->volume());

	if (!slider->currentlyPressed())
		handleLengthString(napp->player()->lengthString());

	if(!napp->player()->current()) return;
	if(slider->currentlyPressed()) return;

	slider->setRange(0, (int)napp->player()->getLength() / 1000 );
	slider->setValue((int)napp->player()->getTime() / 1000 );

	changeStatusbar();
}

void Excellent::sliderMoved(int seconds)
{
	if(napp->player()->current())
		handleLengthString(napp->player()->lengthString(seconds * 1000));
}

void Excellent::skipToWrapper(int second) // wrap int to int _and_ seconds to mseconds
{
	emit skipTo((int)(second*1000));
}

void Excellent::slotLoopTypeChanged(int type)
{
	static const int time = 2000;
	switch (type)
	{
	case Player::None:
		statusBar()->message(i18n("No looping"), time);
		break;
	case Player::Song:
		statusBar()->message(i18n("Song looping"), time);
		break;
	case Player::Playlist:
		statusBar()->message(i18n("Playlist looping"), time);
		break;
	case Player::Random:
		statusBar()->message(i18n("Random play"), time);
	}
}

void Excellent::showMenubar(void)
{
	if(menubarAction->isChecked())
	{
		menuBar()->show();
	}
	else
	{
		KMessageBox::information(this, i18n("<qt>Press %1 to show the menubar.</qt>").arg(menubarAction->shortcut().toString()), TQString(), "Hide Menu warning");
		menuBar()->hide();
	}
}

void Excellent::showVolumeControl(void)
{
	if(volumeAction->isChecked())
		growVolumeControl();
	else
		shrinkVolumeControl();
}

void Excellent::changeStatusbar(void)
{
	if(!napp->player()->current().isNull())
		statusBar()->message(napp->player()->current().title());
}

void Excellent::handleLengthString(const TQString &text)
{
	if(text.right(5) == "00:00" && text.left(5) == "00:00")
	{
		elapsed->setText("--:--");
		total->setText("--:--");
	}
	else
	{
		// Split the length string in to "current" and "elapsed"
		TQStringList tokens = TQStringList::split("/", text);

		elapsed->setText(tokens[0]);
		total->setText(tokens[1]);
	}
}

void Excellent::growVolumeControl(void)
{
	volumeSlider = new L33tSlider(0, 100, 10, 0,Qt::Vertical, mainFrame);
	volumeSlider->setValue(100 - napp->player()->volume());
	volumeSlider->show();
	connect(volumeSlider, TQT_SIGNAL(sliderMoved(int)), TQT_SLOT(changeVolume(int)));
	connect(volumeSlider, TQT_SIGNAL(userChanged(int)), TQT_SLOT(changeVolume(int)));
}

void Excellent::shrinkVolumeControl(void)
{
	delete volumeSlider;
	volumeSlider = 0;
}

void Excellent::changeVolume(int slider)
{
	napp->player()->setVolume(100 - slider);
}

#include "userinterface.moc"
