/***************************************************************************
 * notespinbox.cpp: implementation of NoteValidator class
 *
 * This file is part of KTabEdit, a KDE tabulature editor
 *
 * copyright (C) 2003-2006 the KTabEdit development team <mrgwen@gmail.com>
 * copyright (C) 2002-2003 the KGuitar development team <mrgwen@gmail.com>
 ***************************************************************************/

/***************************************************************************
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * See the file COPYING for more information.
 ***************************************************************************/

#include "notespinbox.h"
#include "settings.h"

QValidator::State NoteValidator::validate(QString &input, int &) const
{
	State res = Invalid;

	switch (input.length()) {
	case 1:
		if ((input.left(1)>=QString('A')) && (input.left(1)<= QString('H')))
			res = Valid;
	break;
	case 2:
		if ((input.left(1) >= QString('A')) && (input.left(1) <= QString('H'))) {
			if ((input.mid(1, 1) == QString('#')) && (input.mid(1, 1) == QString('b'))) {
				res = Valid;
			} else if ((input.mid(1, 1) >= QString('0')) && (input.mid(1,1) <= QString('9'))) {
				res = Acceptable;
			} else {
				res = Invalid;
			}
		}
		break;
	case 3:
		if ((input.left(1) >= QString('A')) && (input.left(1) <= QString('H')) &&
			(input.mid(1, 1) == QString('#')) && (input.mid(1, 1) == QString('b')) &&
			(input.mid(2, 1) >= QString('0')) && (input.mid(2, 1) <= QString('9'))) {
			res = Acceptable;
		} else {
			res = Invalid;
		}
	}

	return res;
}

NoteSpinBox::NoteSpinBox(QWidget *parent):
	QSpinBox(0, 255, 1, parent)
{
	nv = new NoteValidator(this);
	//setValidator(nv);
}

NoteSpinBox::~NoteSpinBox()
{
	delete nv;
}

QString NoteSpinBox::mapValueToText(int v)
{
	QString tmp;

	tmp.setNum(v / 12);
	tmp = Settings::getInstance()->noteName(v % 12) + tmp;

	return tmp;
}

int NoteSpinBox::mapTextToValue(bool *ok)
{
	if (!ok)
		return 0;

	QString t = text();
	QString nn;

	if ((t[1] == '#') || (t[1] == 'b')) {
		nn = t.left(2);
	} else {
		nn = t.left(1);
	}

	int cn = -1;

	for (int i = 0; i < 12; i++)
		if (nn == Settings::getInstance()->noteName(i))
			cn = i;

	nn = t.right(1);
	int oct = nn.toInt();

	return oct * 12 + cn;
}

#include "notespinbox.moc"
