#include "keys.h"

#include <kkeydialog.h>

KeyConnection::~KeyConnection()
{
	for (uint i=0; i<keys.size(); i++) delete keys[i];
}

void KeyConnection::append(const QString &description, const QString &action,
						   const char *member)
{
	uint s = keys.size();
	keys.resize(s+1);
	keys[s] = new KeyData(description, action, member);
}

int KeyConnection::findAction(const QString &action) const
{
	for (uint i=0; i<keys.size(); i++)
		if ( action==keys[i]->a ) return i;
	return -1;
}

//----------------------------------------------------------------------------
KeyConfiguration::KeyConfiguration(uint _nbHumans, KeyConnection &_kn)
: kn(_kn), nbHumans(_nbHumans)
{}

void KeyConfiguration::init(const QArray<const char **> &defaultKeys)
{
	codes.resize(nbHumans * kn.size());
	
	ASSERT( defaultKeys.size()==nbHumans );
	for (uint h=0; h<nbHumans; h++)
		for (uint i=0; i<kn.size(); i++)
		    code(h, i) = KAccel::stringToKey(defaultKeys[h][i]);
}

void KeyConfiguration::init(const KeyConfiguration *kf)
{
	codes.resize(nbHumans * kn.size());
	
	uint nbh = (kf ? kf->nbHumans : 0);
	ASSERT( nbHumans==0 || nbHumans>nbh );
	for (uint h=0; h<nbHumans; h++)
		for (uint i=0; i<kn.size(); i++) {
			if ( h<nbh ) code(h, i) = kf->code(h, i);
			else         code(h, i) = Qt::Key_A; // #### FIXME (find unused keys)
		}
}

void KeyConfiguration::insert()
{
	if ( nbHumans==0 ) return;
	kn.kacc->setConfigGroup(QString("Keys (%1 humans)").arg(nbHumans));
	for (uint h=0; h<nbHumans; h++)
		for (uint i=0; i<kn.size(); i++)
		    kn.kacc->insertItem(kn.description(h, i), kn.action(h, i), code(h, i));
	kn.kacc->readSettings();
}

void KeyConfiguration::configure()
{
	KKeyDialog::configureKeys(kn.kacc);
}

void KeyConfiguration::connect(uint h, QObject *receiver)
{
	if ( nbHumans==0 ) return;
	for (uint i=0; i<kn.size(); i++)
		kn.kacc->connectItem(kn.action(h, i), receiver, kn.member(i), FALSE);
}

void KeyConfiguration::activateBoard(uint h, bool activate)
{
	if ( nbHumans==0 ) return;
	for (uint i=0; i<kn.size(); i++)
		kn.kacc->setItemEnabled(kn.action(h, i), activate);
}

void KeyConfiguration::activateAction(const QString &action, bool activate)
{
	int i = kn.findAction(action);
	ASSERT( i!=-1 );
	
	for (uint h=0; h<nbHumans; h++)
		kn.kacc->setItemEnabled(kn.action(h, i), activate);
}

void KeyConfiguration::remove()
{
	for (uint h=0; h<nbHumans; h++)
		for (uint i=0; i<kn.size(); i++)
		    kn.kacc->removeItem(kn.action(h, i));
}
