#include "shs_graphic.h"
#include <qad_types.h>


SHSGraphic::SHSGraphic(QWidget * parent): Graphic(parent) {
	setHistorySize(-1);
	setAxisType(DateTime);
	setBorderInputsVisible(false);
	setStatusVisible(false);
	setLegendVisible(true);
	setButtons(Graphic::Autofit | Graphic::Grid | Graphic::CursorAxis | Graphic::Fullscreen | Graphic::Configure | Graphic::Save | Graphic::Pause);
#ifdef Q_OS_WINDOWS
	setAntialiasing(true);
	setOpenGL(true);
#endif
	connect(this, SIGNAL(graphicPaintEvent(QPainter*)), this, SLOT(canvasPaint(QPainter*)));
	image_progress.load(":/icons/progress.png");
	all_done = prog_visible = false;
	angle = 0;
	timer_progress = 0;
}


SHSGraphic::~SHSGraphic() {
}


void SHSGraphic::setVariables(const QStringList & v) {
	vars.clear();
	setGraphicsCount(v.size());
	int i = -1;
	foreach (QString n, v) {
		QString l = n;
		if (n.indexOf('=') > 0) {
			n = n.left(n.indexOf('='));
			l = l.right(l.size() - n.size() - 1).trimmed();
			n = n.trimmed();
		}
		setGraphicName(l, ++i);
		vars << QPair<QString, QString>(n, l);
	}
}


QStringList SHSGraphic::variables() const {
	QStringList ret;
	foreach (const auto & i, vars) {
		ret << (i.first + "=" + i.second);
	}
	return ret;
}


QMap<QString, QString> SHSGraphic::variablesMap() const {
	QMap<QString, QString> ret;
	foreach (const auto & i, vars) {
		ret[i.first] = i.second;
	}
	return ret;
}


QStringList SHSGraphic::variableNames() const {
	QStringList ret;
	foreach (const auto & i, vars) {
		ret << i.first;
	}
	return ret;
}


void SHSGraphic::reset() {
	clear();
	done_vars.clear();
	showProgress();
}


void SHSGraphic::showProgress() {
	prog_visible = true;
	if (timer_progress == 0)
		timer_progress = startTimer(25);
}


void SHSGraphic::graphicDone(QString vname) {
	done_vars.insert(vname);
	all_done = (done_vars.size() == vars.size());
	//updateGraphics();
}


void SHSGraphic::buildDebug() {

}


void SHSGraphic::resizeEvent(QResizeEvent * e) {
	Graphic::resizeEvent(e);
	QSizeF sz = preferredIconSize(2, this);
	prog_rect = QRectF(-QPointF(sz.width() / 2., sz.height() / 2.), sz);
}


void SHSGraphic::timerEvent(QTimerEvent * e) {
	if (e->timerId() == timer_progress) {
		if (all_done && timer_progress) {
			killTimer(timer_progress);
			timer_progress = 0;
		}
		angle = (angle + 10) % 360;
		update();
	} else
		Graphic::timerEvent(e);
}


void SHSGraphic::canvasPaint(QPainter * p) {
	if (!prog_visible || all_done || !canvas || image_progress.isNull() || vars.isEmpty()) return;
	p->setRenderHint(QPainter::SmoothPixmapTransform);
	p->translate(canvas->width(), 0);
	p->translate(-prog_rect.width() * 0.7, prog_rect.height() * 0.7);
	p->rotate(angle);
	p->drawImage(prog_rect, image_progress);
}
