#include "graphic_analysis_stat.h"

#include "graphic_analysis.h"
#include "ui_graphic_analysis_stat.h"

#include <pistatistic.h>
#include <qad_types.h>


GraphicAnalysisStatistics::GraphicAnalysisStatistics(QWidget * parent): QDialog(parent) {
	ui = new Ui::GraphicAnalysisStatistics();
	ui->setupUi(this);
	int fh = qMax<int>(fontMetrics().height(), 22);
	QSize sz(fh * 2.5, fh);
	ui->comboGraphic->setIconSize(sz);
}


GraphicAnalysisStatistics::~GraphicAnalysisStatistics() {
	delete ui;
}


void GraphicAnalysisStatistics::show(GraphicAnalysis * g, GraphicRanges::Range r) {
	source = g;
	range  = r;
	if (range.isEmpty()) range = source->rangeAll();
	ui->comboGraphic->clear();
	for (int i = 0; i < source->graphicsCount(); ++i) {
		auto g = source->graphic(i);
		ui->comboGraphic->addItem(g.icon, g.name);
	}
	QDialog::exec();
}


void GraphicAnalysisStatistics::changeEvent(QEvent * e) {
	QDialog::changeEvent(e);
	if (e->type() == QEvent::LanguageChange) {
		ui->retranslateUi(this);
		return;
	}
}


void GraphicAnalysisStatistics::on_comboGraphic_currentIndexChanged(int index) {
	if (index < 0 || !source) return;
	auto setNum     = [](double v, QLineEdit * le) { le->setText(QString::number(v)); };
	const auto data = source->graphicData(index);
	QPolygonF in;
	for (const auto & i: data) {
		if ((i.x() >= range.start) && (i.x() <= range.end)) in << i;
	}
	auto br = in.boundingRect();
	setNum(br.left(), ui->lineXMin);
	setNum(br.right(), ui->lineXMax);
	setNum(br.top(), ui->lineYMin);
	setNum(br.bottom(), ui->lineYMax);
	setNum(in.size(), ui->linePoints);
	PIVector<double> stat_in;
	in.reserve(256);
	for (const auto & i: in)
		stat_in << i.y();
	PIStatisticd stat;
	stat.calculate(stat_in);
	setNum(stat.mean, ui->lineMean);
	setNum(stat.variance, ui->lineVariance);
	setNum(stat.skewness, ui->lineSkewness);
	setNum(stat.kurtosis, ui->lineKurtosis);
}
