
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqcheckbox.h>
#include <noatun/app.h>

#include <kdialog.h>
#include <tdelocale.h>
#include <tdeconfig.h>
#include <tdelistview.h>
#include <kcombobox.h>
#include <knuminput.h>

#include "irprefs.h"
#include "lirc.h"

class CommandItem : public TQListViewItem
{
public:
	CommandItem(TQListViewItem *remote, const TQString &name,
	            IRPrefs::Action action, int interval)
		: TQListViewItem(remote, name, IRPrefs::actionName(action),
		                interval ? TQString().setNum(interval) : TQString()),
		  m_name(remote->text(0) + "::" + name),
		  m_action(action),
		  m_interval(interval)
	{
	}

	const TQString &name() const { return m_name; }
	IRPrefs::Action action() const { return m_action; }
	int interval() const { return m_interval; }
	void setAction(IRPrefs::Action action)
	{
		setText(1, IRPrefs::actionName(action));
		m_action = action;
	}
	void setInterval(int interval)
	{
		setText(2, interval ? TQString().setNum(interval) : TQString());
		m_interval = interval;
	}

private:
	TQString m_name;
	IRPrefs::Action m_action;
	int m_interval;
};

Lirc *IRPrefs::s_lirc = 0;
bool IRPrefs::s_configRead = false;
TQMap<TQString, IRPrefs::Command> IRPrefs::s_commands;

IRPrefs::IRPrefs(TQObject *parent)
	: CModule(i18n("Infrared Control"), i18n("Configure Infrared Commands"), "remote", parent)
{
	TQGridLayout *layout = new TQGridLayout(this, 3, 5, KDialog::marginHint(), KDialog::spacingHint());
	layout->setColStretch(1, 1);

	TQLabel *label = new TQLabel(i18n("Remote control &commands:"), this);
	layout->addMultiCellWidget(label, 0, 0, 0, 4);

	label->setBuddy(m_commands = new TDEListView(this));
	layout->addMultiCellWidget(m_commands, 1, 1, 0, 4);

	label = new TQLabel(i18n("&Action:"), this);
	layout->addWidget(label, 2, 0);

	label->setBuddy(m_action = new KComboBox(this));
	m_action->setEnabled(false);
	layout->addWidget(m_action, 2, 1);

	m_repeat = new TQCheckBox(i18n("&Repeat"), this);
	m_repeat->setEnabled(false);
	layout->addWidget(m_repeat, 2, 2);

	label = new TQLabel(i18n("&Interval:"), this);
	layout->addWidget(label, 2, 3);

	label->setBuddy(m_interval = new KIntSpinBox(this));
	m_interval->setMinValue(1);
	m_interval->setMaxValue(0xff);
	m_interval->setValue(10);
	m_interval->setEnabled(false);
	layout->addWidget(m_interval, 2, 4);

	connect(s_lirc, TQT_SIGNAL(remotesRead()), TQT_SLOT(reopen()));
	connect(m_commands,
	        TQT_SIGNAL(selectionChanged(TQListViewItem *)),
			TQT_SLOT(slotCommandSelected(TQListViewItem *)));
	connect(m_action,
	        TQT_SIGNAL(activated(int)),
			TQT_SLOT(slotActionActivated(int)));
	connect(m_repeat,
	        TQT_SIGNAL(toggled(bool)),
			TQT_SLOT(slotRepeatToggled(bool)));
	connect(m_interval,
	        TQT_SIGNAL(valueChanged(int)),
			TQT_SLOT(slotIntervalChanged(int)));

	reopen();
}

void IRPrefs::save()
{
	TDEConfig *c = kapp->config();
	TDEConfigGroupSaver groupSaver(c, "Infrared");
	c->writeEntry("CommandCount", s_commands.count());
	int i = 1;
	for (TQMap<TQString, Command>::ConstIterator it = s_commands.begin(); it != s_commands.end(); ++it)
	{
		c->writePathEntry(TQString("Command_%1").arg(i), it.key());
		c->writeEntry(TQString("Action_%1").arg(i), (int)((*it).action));
		c->writeEntry(TQString("Interval_%1").arg(i), (*it).interval);
		++i;
	}
}

void IRPrefs::reopen()
{
	readConfig();

	TQStringList remotes = s_lirc->remotes();
	m_commands->clear();
	while (m_commands->columns()) m_commands->removeColumn(0);
	if (!remotes.count())
	{
		m_commands->addColumn(i18n("Sorry"));
		m_commands->setSorting(-1);
		if (s_lirc->isConnected())
		{
			new TQListViewItem(m_commands, i18n("You do not have any remote control configured."));
			new TQListViewItem(m_commands, i18n("Please make sure lirc is setup correctly."));
		}
		else
		{
			new TQListViewItem(m_commands, i18n("Connection could not be established."));
			new TQListViewItem(m_commands, i18n("Please make sure lirc is setup correctly and lircd is running."));
		}
		m_commands->setEnabled(false);
		return;
	}
	m_commands->setEnabled(true);
	m_commands->addColumn(i18n("Button"));
	m_commands->addColumn(i18n("Action"));
	m_commands->addColumn(i18n("Interval"));
	m_commands->setSorting(0);
	for (TQStringList::ConstIterator it = remotes.begin(); it != remotes.end(); ++it)
	{
		TQListViewItem *remote = new TQListViewItem(m_commands, *it);
		const TQStringList &buttons = s_lirc->buttons(*it);
		for (TQStringList::ConstIterator btn = buttons.begin(); btn != buttons.end(); ++btn)
		{
			TQString key = *it + "::" + *btn;
			if (s_commands.contains(key))
				new CommandItem(remote, *btn, s_commands[key].action, s_commands[key].interval);
			else
				new CommandItem(remote, *btn, None, 0);
		}
		remote->setOpen(true);
	}

	m_action->clear();
	for (int i = 0; ; ++i)
	{
		TQString action = actionName((Action)i);
		if (action.isNull())
			break;
		if (action.isEmpty())
			m_action->insertItem(i18n("None"));
		else
			m_action->insertItem(action);
	}


}

void IRPrefs::slotCommandSelected(TQListViewItem *item)
{
	CommandItem *cmd = dynamic_cast<CommandItem *>(item);
	if (cmd)
	{
		m_action->setCurrentItem((int)(cmd->action()));
		m_repeat->setChecked(cmd->interval());
		if (cmd->interval())
			m_interval->setValue(cmd->interval());
		else
		{
			m_interval->setValue(10);
			cmd->setInterval(0); // HACKHACKHACK
		}
		m_action->setEnabled(true);
		m_repeat->setEnabled(cmd->action() != None);
		m_interval->setEnabled(cmd->interval());
	}
	else
	{
		m_action->setEnabled(false);
		m_repeat->setEnabled(false);
		m_interval->setEnabled(false);
	}
}

void IRPrefs::slotActionActivated(int action)
{
	CommandItem *cmd = dynamic_cast<CommandItem *>(m_commands->currentItem());
	if (!cmd)
		return; // Shouldn't happen
	cmd->setAction((Action)action);
	if (cmd->action() == None)
	{
		cmd->setInterval(0);
		m_repeat->setChecked(false);
		m_repeat->setEnabled(false);
		m_interval->setEnabled(false);
	}
	else
	{
		m_repeat->setEnabled(true);
		m_interval->setEnabled(cmd->interval());
	}
	s_commands[cmd->name()].action = cmd->action();
	s_commands[cmd->name()].interval = 0;
}

void IRPrefs::slotRepeatToggled(bool value)
{
	CommandItem *cmd = dynamic_cast<CommandItem *>(m_commands->currentItem());
	if (!cmd)
		return; // Shouldn't happen
	cmd->setInterval(value ? 10 : 0);
	s_commands[cmd->name()].interval = cmd->interval();
	m_interval->setEnabled(value);
}

void IRPrefs::slotIntervalChanged(int value)
{
	CommandItem *cmd = dynamic_cast<CommandItem *>(m_commands->currentItem());
	if (!cmd)
		return; // Shouldn't happen
	cmd->setInterval(value);
	s_commands[cmd->name()].interval = cmd->interval();
}

const TQString IRPrefs::actionName(Action action)
{
	switch (action)
	{
		case None:
			return TQString("");
		case Play:
			return i18n("Play");
		case Stop:
			return i18n("Stop");
		case Previous:
			return i18n("Back");
		case Next:
			return i18n("Next");
		case VolumeDown:
			return i18n("Volume Down");
		case VolumeUp:
			return i18n("Volume Up");
		case Mute:
			return i18n("Mute");
		case Pause:
			return i18n("Pause");
		case SeekBackward:
			return i18n("Seek Backward");
		case SeekForward:
			return i18n("Seek Forward");
		case ShowPlaylist:
			return i18n("Show Playlist");
		case NextSection:
			return i18n("Next Section");
		case PreviousSection:
			return i18n("Previous Section");
	}
	return TQString();
}

void IRPrefs::readConfig()
{
	if (s_configRead)
		return;
	TDEConfig *c = kapp->config();
	TDEConfigGroupSaver groupSaver(c, "Infrared");
	int count = c->readNumEntry("CommandCount");
	for (int i = 1; i <= count; ++i)
	{
		Command cmd;
		cmd.action = (Action)(c->readNumEntry(TQString("Action_%1").arg(i)));
		cmd.interval = c->readNumEntry(TQString("Interval_%1").arg(i));
		s_commands.insert(c->readPathEntry(TQString("Command_%1").arg(i)), cmd);
	}
	s_configRead = true;
}

IRPrefs::Action IRPrefs::actionFor(const TQString &remote, const TQString &button, int repeat)
{
	readConfig();
	Command cmd = s_commands[remote + "::" + button];
	if ((cmd.interval == 0 && repeat == 0)
		|| (cmd.interval != 0 && repeat % cmd.interval == 0))
		return cmd.action;
	else
		return None;
}

#include "irprefs.moc"


