#include "pref.h"

#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
//#include <kdebug.h>
#include <qlayout.h>
#include <qlabel.h>
#include "cmodule.h"

NoatunPreferences::NoatunPreferences(QWidget *parent)
    : KDialogBase(TreeList, i18n("Preferences - Noatun"),
                  Ok|Apply|Cancel|Help, Ok, parent, 0, false, true)
{
	resize(640, 480); // KDE is required to support 800x600 min.
	setShowIconsInTreeList(true);
	setRootIsDecorated(false);
}

void NoatunPreferences::slotOk()
{
	slotApply();
	hide();
}

void NoatunPreferences::show()
{
	for (CModule *i=mModules.first(); i != 0; i=mModules.next())
		i->reopen();
	KDialogBase::show();
}

void NoatunPreferences::show(CModule *page)
{
	for (CModule *i=mModules.first(); i != 0; i=mModules.next())
		i->reopen();
	int index = pageIndex( static_cast<QWidget *>(page->parent()) );
//	kdDebug(66666) << k_funcinfo << "index=" << index << endl;
	if (index != -1)
		showPage(index);
	KDialogBase::show();
}


void NoatunPreferences::slotApply()
{
	for (CModule *i=mModules.first(); i != 0; i=mModules.next())
		i->save();
}

void NoatunPreferences::add(CModule *page)
{
	mModules.append(page);
}

void NoatunPreferences::remove(CModule *page)
{
	mModules.removeRef(page);
}

CModule::CModule(const QString &name, const QString &description, const QString &icon, QObject *owner)
	: QWidget(napp->preferencesBox()->addPage(name,
	                                          description,
	                                          KGlobal::iconLoader()->loadIcon(icon,
	                                                                          KIcon::Small,
	                                                                          0, KIcon::DefaultState,
	                                                                          0, true)))
{
	if (owner)
		connect(owner, SIGNAL(destroyed()), SLOT(ownerDeleted()));

	napp->preferencesBox()->add(this);

	QFrame *page=static_cast<QFrame*>(parent());
	(new QHBoxLayout(page))->addWidget(this);
}

CModule::~CModule()
{
	// TODO When kdialogbase is fixed, delete the parent QFrame, and
	// all traces of the related page
	napp->sendPostedEvents();
	napp->preferencesBox()->remove(this);
}

void CModule::ownerDeleted()
{
	QObject *p=parent();
	delete this;
	p->deleteLater();
}

#include <noatun/pref.moc>
