#include <QtWidgets>
#include "controls.h"

Controls::Controls(QWidget *parent) :
	QWidget(parent)
{
	QGridLayout *eLayout = new QGridLayout;
	eLayout->addWidget(new QLabel("label 1"), 0, 0);
	eLayout->addWidget(new QLabel("label 2"),  1, 0);
	eLayout->addWidget(e1 = new QLineEdit, 0, 1);
	eLayout->addWidget(e2  = new QLineEdit, 1, 1);

	QHBoxLayout *rLayout = new QHBoxLayout;
	rLayout->addWidget(r1   = new QRadioButton("rb 1"));
	rLayout->addWidget(r2 = new QRadioButton("rb 2"));
	QGroupBox *rGroup = new QGroupBox("RB Group");
	rGroup->setLayout(rLayout);

	QGridLayout *edLayout = new QGridLayout;
	edLayout->addWidget(rg[0] = new QRadioButton("1"), 0, 0);
	edLayout->addWidget(rg[1] = new QRadioButton("2"), 1, 0);
	edLayout->addWidget(rg[2] = new QRadioButton("3"), 0, 1);
	edLayout->addWidget(rg[3] = new QRadioButton("4"), 1, 1);
	QGroupBox *rgGroup = new QGroupBox("RB Group2");
	rgGroup->setLayout(edLayout);

	QHBoxLayout *buttonsLayout = new QHBoxLayout;
	buttonsLayout->addWidget(save   = new QPushButton("Save"));
	buttonsLayout->addWidget(revert = new QPushButton("Revert"));

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addLayout(eLayout);
	mainLayout->addWidget(rGroup);
	mainLayout->addWidget(rgGroup);
	mainLayout->addLayout(buttonsLayout);
	setLayout(mainLayout);

	QObject::connect(revert, SIGNAL(clicked()), SLOT(doRevert()));
	QObject::connect(save,   SIGNAL(clicked()), SLOT(doSave()));

	settings.setIniCodec("UTF-8");
	doRevert();
}

void Controls::doRevert()
{
	e1->setText(settings.value("e1").toString());
	e2->setText(settings.value("e2").toString());
	(settings.value("r2").toBool() ? r2 : r1)->setChecked(true);
	rg[qMin<size_t>(settings.value("rg").toUInt(), sizeof(rg)/sizeof(*rg)-1)]->setChecked(true);
}

void Controls::doSave()
{
	settings.setValue("e1", e1->text());
	settings.setValue("e2", e2->text());
	settings.setValue("r2", r2->isChecked());
	uint i = sizeof(rg)/sizeof(*rg);
	while (--i)
		if (rg[i]->isChecked())
			break;
	settings.setValue("rg", i);
}
