#include "selection.h"
#include "conf.h"

#include <KModifierKeyInfo>
#include <QApplication>
#include <QClipboard>


namespace Dict {

void SelectionConf::read()
{
	ConfGroup group("Selections");

	yank = group.readEntry("Yank", false);
	local = group.readEntry("Local", true);
	remote = group.readEntry("Remote", true);

	minLen = group.readEntry("MinLen", 2);
	maxLen = group.readEntry("MaxLen", 80);
	warnLen = group.readEntry("WarnLen", 40);
	modifier = group.readEntry("ModifierKey", 0);
}

void SelectionConf::write()
{
	ConfGroup group("Selections");

	group.writeEntry("Yank" , yank);
	group.writeEntry("Local" , local);
	group.writeEntry("Remote" , remote);

	group.writeEntry("MinLen", minLen);
	group.writeEntry("MaxLen", maxLen);
	group.writeEntry("WarnLen", warnLen);
	group.writeEntry("ModifierKey", modifier);
}

Selection::Selection()
{
	clipboard = QApplication::clipboard();
	select.yank = false;
	modifier = (Qt::Key)0;
	modinfo = 0;
}

void Selection::setup()
{
	bool oldyank = select.yank;
	select.read();
	bool newyank = select.yank;
	select.yank = oldyank;
	set(newyank);

	switch (select.modifier) {
	case None: default: modifier = (Qt::Key)0; break;
	case Ctrl: modifier = Qt::Key_Control; break;
	case Alt: modifier = Qt::Key_Alt; break;
	case Meta: modifier = Qt::Key_Meta; break;
	case Shift: modifier = Qt::Key_Shift; break;
	}
	if (modifier && !modinfo)
		modinfo = new KModifierKeyInfo(this);
}

void Selection::set(bool yank)
{
	if (select.yank == yank)
		return;
	else
		select.yank = yank;

	if (yank)
		connect(clipboard, SIGNAL(selectionChanged()), SLOT(selection()));
	else
		clipboard->disconnect(this);

	select.write();
}

static QString last;

QString Selection::current()
{
	return clipboard->text(QClipboard::Selection).left(select.maxLen);
}

void Selection::selection()
{
	last = current();

	if (modifier && !modinfo->isKeyPressed(modifier))
		return;

	bool owner = clipboard->ownsSelection();
	if (!select.local && owner)
		return;
	if (!select.remote && !owner)
		return;

	if (last.length() < select.minLen || last.length() >= select.maxLen)
		return;

	emit selectionChanged(last);
}

}
