#include "mapitemellipse.h"

#include <math.h>


MapItemEllipse::MapItemEllipse(const QRectF & r) {
	setEllipse(r);
}


MapItemEllipse::MapItemEllipse(const QPointF & p, double rx, double ry) {
	setEllipse(p, rx, ry);
}


void MapItemEllipse::setStartAngle(double a) {
	sa = a;
	rebuild();
	updateParent();
}


void MapItemEllipse::setEndAngle(double a) {
	ea = a;
	rebuild();
	updateParent();
}


void MapItemEllipse::setEllipse(const QRectF & r) {
	rct = r;
	rebuild();
	updateParent();
}


void MapItemEllipse::setEllipse(const QPointF & p, double rx, double ry) {
	rct.setWidth(rx * 2.);
	rct.setHeight(ry * 2.);
	rct.moveCenter(p);
	rebuild();
	updateParent();
}


void MapItemEllipse::draw(QPainter * p) {
	p->setPen(pen());
	p->setBrush(brush());
	QPolygonF dp(pol);
	double us = unitScale();
	for (auto & i: dp)
		i = QPointF(i.x(), -i.y()) / us;
	p->drawPolygon(dp);
	setBoundingRect(dp.boundingRect());
}


void MapItemEllipse::rebuild() {
	pol.clear();
	QPointF c     = rct.center();
	double starta = sa, enda = ea;
	bool full = qFuzzyCompare(starta, enda);
	if (!full) pol << c;
	double w = rct.width() / 2., h = rct.height() / 2.;
	static double deg2rad = M_PI / 180.;
	if (full) {
		starta = 0.;
		enda   = 360.;
	} else {
		if (enda < starta) qSwap(starta, enda);
	}
	const double astep = 3.;
	for (double a = starta; a < enda + astep; a += astep) {
		if (a > enda) a = enda;
		QPointF p(sin(a * deg2rad) * w, cos(a * deg2rad) * h);
		pol << (c + p);
	}
	if (!full) pol << c;
}
