#include "signaturewidget.h"
#include "integral.h"

#define LABEL_TO_ARRAY(I) labels[I] = ui.label##I

SignatureWidget::SignatureWidget(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	LABEL_TO_ARRAY(0);	LABEL_TO_ARRAY(1);	LABEL_TO_ARRAY(2); LABEL_TO_ARRAY(3);
	LABEL_TO_ARRAY(4);	LABEL_TO_ARRAY(5);	LABEL_TO_ARRAY(6); LABEL_TO_ARRAY(7);
	LABEL_TO_ARRAY(8);	LABEL_TO_ARRAY(9);	LABEL_TO_ARRAY(10); LABEL_TO_ARRAY(11);
	LABEL_TO_ARRAY(12);	LABEL_TO_ARRAY(13);	LABEL_TO_ARRAY(14); LABEL_TO_ARRAY(15);

	for (int i=0; i < 16; i++)
	{
		labels[i]->setAutoFillBackground(true);
		labels[i]->setMinimumWidth(20);
	}
}


void SignatureWidget::updateSignature(integralBuffer *integral, int x, int y, SignatureParameters sParams)
{
	if (x < 6 || x >= integral->w - 6 || y < 6 || y >= integral->w - 6)
		return;

	int dx,dy;
	int c = 0;
	uint16_t mean;
	uint32_t sdev;
	uint32_t baseEpsilon;

	int min = G12BUFFER_MAX_VALUE;
	int max = 0;
	for (dy = -3; dy <= 3; dy += 2)
	{
		for (dx = -3; dx <= 3; dx += 2)
		{
			uint32_t value = getRectangleValue(integral, y + dy - 2, x + dx - 2, y + dy + 2, x + dx + 2 );
			value /= 25;
			data[c] = value;
			if (value > max)
				max = value;
			if (value < min)
				min = value;
			c++;
		}
	}

	signature_t sig = signature3piece(data, &sParams, &mean, &sdev, &baseEpsilon);

	if (min == max)
		max = min + 1;
	for (c = 0; c < 16; c++)
	{
		QPalette pal = labels[c]->palette();
		uint32_t grey = (data[c] - min) * 256 / (max - min);
/*		grey = (grey * 127) / sdev ;
		grey += 128;*/
		if (grey < 0) grey = 0;
		if (grey > 255) grey = 255;
		pal.setColor(labels[c]->backgroundRole(), QColor(grey, grey, grey));
		pal.setColor(QPalette::WindowText, grey > 128 ? QColor(0, 0, 0) : QColor(255, 255, 255));

		labels[c]->setPalette(pal);
		labels[c]->setNum((int)(data[c] - mean));
	}

	ui.position->setText(QString("(%1,%2)").arg(x).arg(y));
	char s[17];
	prettyPrintSignature(sig, s, sizeof(s));
	ui.value->setText(QString("%1").arg(s));

}


SignatureWidget::~SignatureWidget()
{

}
