#include "touchbuttframe.h"


TouchButtFrame::TouchButtFrame(QWidget * parent, Qt::Orientation orientation): QFrame(parent) {
	id_click = id_set = -1;
	TouchButton b;
	colr = b.noColor();
	colg = b.yesColor();
	colw = b.grayColor();
	colp = b.downColor();
	setFrameShape(QFrame::StyledPanel);
	lay = new QBoxLayout(QBoxLayout::LeftToRight);
	lay->setContentsMargins(0, 0, 0, 0);
	if (orientation == Qt::Vertical) lay->setDirection(QBoxLayout::TopToBottom);
}


void TouchButtFrame::addButton(const QString & caption) {
	TouchButton * butt = new TouchButton(lay->count(), caption);
	butt->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
	butt->setCheckable(true);
	butt->setAutoExclusive(true);
	// butt->setAutoFillBackground(true);
	lay->addWidget(butt);
	this->setLayout(lay);
	connect(butt, SIGNAL(clickedID(int)), SLOT(butt_click(int)));
	connect(butt, SIGNAL(toggledID(int, bool)), SLOT(butt_toggle(int, bool)));
}


void TouchButtFrame::resetColors() {
	for (int i = 0; i < lay->count(); ++i) {
		button(i)->setYesColor(colg);
		button(i)->setNoColor(colr);
		button(i)->setGrayColor(colw);
		button(i)->setDownColor(colp);
	}
}


void TouchButtFrame::deleteButtons() {
	while (!lay->isEmpty())
		delete button(0);
}


void TouchButtFrame::setButtons(const QStringList & captions) {
	int cur = currentButton();
	deleteButtons();
	for (int i = 0; i < captions.size(); ++i)
		addButton(QString(captions.at(i)).replace("\\n", "\n"));
	if (button(cur) != 0)
		button(cur)->setChecked(true);
	else if (!captions.isEmpty())
		button(0)->setChecked(true);
	resetColors();
}


void TouchButtFrame::setCurrentButton(int index) {
	if (button(index) != 0) {
		if (currentButton() != -1) button(currentButton())->setChecked(false);
		button(index)->setChecked(true);
	}
}


int TouchButtFrame::currentButton() {
	for (int i = 0; i < buttonsCount(); ++i)
		if (button(i)->isChecked()) return i;
	return -1;
}


QStringList TouchButtFrame::buttons() {
	QStringList l;
	for (int i = 0; i < lay->count(); ++i)
		l.append(button(i)->text().replace("\n", "\\n"));
	return l;
}


TouchButton * TouchButtFrame::button(int index) {
	if (index >= 0 && index < lay->count()) return (qobject_cast<TouchButton *>(lay->itemAt(index)->widget()));
	return 0;
}
