#ifndef SCALER2D_H
#define SCALER2D_H

#include <QPoint>
#include <Indoor/geo/Point2.h>
#include <Indoor/geo/BBox2.h>

class Scaler2D {

private:

	Point2 screenSize = Point2(400,400);
	Point2 center_m = Point2(0,0);
	float rotation_rad = 0.0f;
	float scaleFactor = 1;

	BBox2 mapBBox_m;

public:

	Scaler2D() {
		;
	}

	/** set the screen's size (in pixel) */
	void setScreenSize(const float w_px, const float h_px) {
		this->screenSize = Point2(w_px, h_px);
	}

	/** change the point displayed within the center of the screen */
	void setCenter(const float x_m, const float y_m) {
		this->center_m = Point2(x_m, y_m);
	}

	/** change the point displayed within the center of the screen */
	void setCenterM(const Point2 center_m) {
		this->center_m = center_m;
		if (!mapBBox_m.isInvalid()) {
			if (this->center_m.x < mapBBox_m.getMin().x) {this->center_m.x = mapBBox_m.getMin().x;}
			if (this->center_m.y < mapBBox_m.getMin().y) {this->center_m.y = mapBBox_m.getMin().y;}
			if (this->center_m.x > mapBBox_m.getMax().x) {this->center_m.x = mapBBox_m.getMax().x;}
			if (this->center_m.y > mapBBox_m.getMax().y) {this->center_m.y = mapBBox_m.getMax().y;}
		}
	}

	/** change the point displayed within the center of the screen */
	void setCenterPX(const Point2 center_px) {
		setCenterM(pxToM(center_px));
	}

	Point2 getCenterPX() const {
		return mToPX(this->center_m);
	}

	/** set the map's rotation in radians */
	void setRotation(const float rad) {
		this->rotation_rad = rad;
	}

	/** set the map's scaling */
	void setScale(const float scale) {
		this->scaleFactor = scale;
		if (this->scaleFactor < 0.1) {this->scaleFactor = 0.1;}
		if (this->scaleFactor > 4.0) {this->scaleFactor = 4.0;}
	}

	void mulScale(const float mod) {
		setScale(this->scaleFactor * mod);
	}

	/** set the map's bbox. used to prevent from scrolling outside of the map */
	void setMapBBox(const BBox2 bbox_m) {
		this->mapBBox_m = bbox_m;
	}

public:

	float mToPX(const float m) const {
		return m * scaleFactor * (screenSize.x * 0.01);
	}

	float pxToM(const float px) const {
		return px / scaleFactor / (screenSize.x * 0.01);
	}

	Point2 pxToM(const Point2 pt) const {
		return Point2(pxToM(pt.x), pxToM(pt.y));
	}

	Point2 mToPX(const Point2 pt) const {
		return Point2(mToPX(pt.x), mToPX(pt.y));
	}

	/** convert map to screen coordinates */
	Point2 mapToScreen(const Point2 pt_m) const {

		Point2 pt = pt_m;

		// move to (0,0)
		pt -= center_m;

		// rotate
		pt = Point2(
			std::cos(rotation_rad) * pt.x - std::sin(rotation_rad) * pt.y,
			std::sin(rotation_rad) * pt.x + std::cos(rotation_rad) * pt.y
		);

		// scale
		pt.x = mToPX(pt.x);
		pt.y = mToPX(pt.y);


		// add screen-center
		pt += screenSize/2;

		// negate y
		pt.y = screenSize.y - pt.y;

		// done
		return pt;

	}

};

#endif // SCALER2D_H
