#include <QStyleFactory>
#include <QBoxLayout>
#include "groupswidget.h"


GroupsWidget::GroupsWidget(QWidget * parent): QWidget(parent) {
	setLayout(new QBoxLayout(QBoxLayout::LeftToRight));
	layout()->setContentsMargins(layout()->contentsMargins().left(), 0,
								 layout()->contentsMargins().right(), 0);
	layout()->setSpacing(0);
	fusion = QStyleFactory::create("Fusion");
	setGroupsCount(16);
}


GroupsWidget::~GroupsWidget() {
}


void GroupsWidget::setGroupsCount(int cnt) {
	qDeleteAll(buttons);
	buttons.clear();
	bits.resize(cnt);
	for (int i = 0; i < cnt; ++i) {
		SHSButton * b = new SHSButton(i);
		b->setCheckable(true);
		connect(b, SIGNAL(toggled(bool)), b, SLOT(setStateYesOrGray(bool)));
		connect(b, SIGNAL(clicked(bool)), this, SIGNAL(changed()));
		b->setText(QString::number(i + 1).rightJustified(2, ' '));
		layout()->addWidget(b);
		b->setChecked(bits[i]);
		b->setStyle(fusion);
		buttons << b;
	}
}


int GroupsWidget::groupsCount() const {
	return bits.bitSize();
}


void GroupsWidget::setGroupsU(ushort g) {
	int cnt = piMini(buttons.size(), 16);
	for (int i = 0; i < cnt; ++i)
		buttons[i]->setChecked((g & (1 << i)) > 0);
	emit changed();
}


ushort GroupsWidget::groupsU() const {
	ushort ret = 0;
	int cnt = piMini(buttons.size(), 16);
	for (int i = 0; i < cnt; ++i)
		if (buttons[i]->isChecked())
			ret |= (1 << i);
	return ret;
}


void GroupsWidget::setGroups(QByteArray d) {
	if (d.isEmpty())
		d.fill(0, bits.byteSize());
	memcpy(bits.data(), d.data(), piMini(d.size(), bits.byteSize()));
	int cnt = piMini(buttons.size(), bits.bitSize());
	for (int i = 0; i < cnt; ++i)
		buttons[i]->setChecked(bits[i]);
	emit changed();
}


PIBitArray GroupsWidget::groups() const {
	int cnt = piMini(buttons.size(), bits.bitSize());
	for (int i = 0; i < cnt; ++i)
		bits.writeBit(i, buttons[i]->isChecked());
	return bits;
}


bool GroupsWidget::contains(int group) const {
	//return (groups() & (1 << group)) > 0;
	if (group < 0 || group >= buttons.size()) return false;
	return buttons[group]->isChecked();
}


void GroupsWidget::setButton(int index, bool on) {
	if (index < 0 || index >= buttons.size()) return;
	buttons[index]->setChecked(on);
}


bool GroupsWidget::isNull() const {
	int cnt = piMini(buttons.size(), bits.bitSize());
	for (int i = 0; i < cnt; ++i)
		if (buttons[i]->isChecked()) return false;
	return true;
}
