#include "histogramwidget.h"
#include "qpainter.h"

HistogramWidget::HistogramWidget(QWidget *parent)
    : QWidget(parent)
{
	ui.setupUi(this);
	hist = NULL;
}

void HistogramWidget::paintEvent(QPaintEvent *event)
{
	int i,j;
	if (hist == NULL)
		return;
	QPainter painter(this);
	painter.setPen(Qt::black);
	int h = this->size().height();
	int w = this->size().width();

	if (h == 0) h = 1;
	double x = 1;
	double dx = (double)(G12BUFFER_MAX_VALUE - 2) / w;

	int globalmax = 0;
	int where = -1;
	for (i = 1; i < G12BUFFER_MAX_VALUE - 1; i++)
	{
		if (hist->data[i] > globalmax)
		{
			globalmax = hist->data[i];
			where = i;
		}
	}

	double scale = (double)h / (globalmax + 1);


	for (i = 1; i < w - 1; i++)
	{
		int step = (int)dx + 1 ;
		int max  =  0;
		int min  =  0xFFFF;
		int sum =   0;
		int count;

		for(j = x, count = 0; j < x + step && j < (G12BUFFER_MAX_VALUE - 1); j++, count ++)
		{
			int val = hist->data[j];
			sum += val;
			if (val > max) max = val;
			if (val < min) min = val;
		}

		sum /= count;
		//printf("%d %d -> %d\n", val);
		painter.setPen(Qt::blue);
		painter.drawLine(i,h - 1,i,h - 1 - (max * scale));
		painter.setPen(i == selectedH ? Qt::yellow : Qt::black);
		painter.drawLine(i,h - 1,i,h - 1 - (sum * scale));
		painter.setPen(Qt::green);
		painter.drawLine(i,h - 1,i,h - 1 - (min * scale));
		x += dx;
	}
}

void HistogramWidget::notifyBufferChange(G12Buffer *buf)
{


	selectedH = 0;
	if (buf == NULL)
		return;
	if (hist != NULL)
		histogramDelete(hist);
	hist = histogramCreateFromG12Buffer(buf);


	int globalmax = 0;
	int where = -1;
	for (int i = 1; i < G12BUFFER_MAX_VALUE - 1; i++)
	{
		if (hist->data[i] > globalmax)
		{
			globalmax = hist->data[i];
			where = i;
		}
	}

	emit maximumChanged(QString::number(globalmax));
	emit leftChanged(QString::number(0));
	emit rightChanged(QString::number(G12BUFFER_MAX_VALUE));
	this->update();




}

void HistogramWidget::mouseMoveEvent(QMouseEvent *event)
{
	int x = event->x();
//	this->repaint();
	if (x > 0 && x < this->size().width())
	{
		selectedH = x;
		this->update();
	}
}


HistogramWidget::~HistogramWidget()
{

}
