#include "alignedtextitem.h"

#include "blockbase.h"

#include <QApplication>
#include <QDebug>
#include <QPainter>


AlignedTextItem::AlignedTextItem(QGraphicsItem * parent): QGraphicsItem(parent), text_(this) {
	align_ = Qt::AlignTop | Qt::AlignHCenter;
	text_.setData(bvidVisualizeSelection, true);
	setFont(font());
	_move();
}


AlignedTextItem::AlignedTextItem(const QString & text, QGraphicsItem * parent): QGraphicsItem(parent), text_(this) {
	align_ = Qt::AlignTop | Qt::AlignHCenter;
	text_.setData(bvidVisualizeSelection, true);
	setFont(font());
	setText(text);
}

void AlignedTextItem::setFont(const QFont & f) {
	font_ = f;
	text_.setFont(sceneFont(f));
	_move();
}


QFont AlignedTextItem::sceneFont(const QFont & f) {
	QFont ret  = f;
	double scl = 16. / fontHeight();
	ret.setPointSizeF(ret.pointSizeF() * scl);
	return ret;
}


QPointF AlignedTextItem::_point(Qt::Alignment a) const {
	QRectF br = text_.boundingRect();
	QPointF ret;
	switch (Qt::AlignmentFlag(int(align_ & Qt::AlignHorizontal_Mask))) {
	case Qt::AlignRight: ret.rx() = br.left(); break;
	case Qt::AlignHCenter: ret.rx() = br.center().x(); break;
	case Qt::AlignLeft: ret.rx() = br.right(); break;
	default: break;
	}
	switch (Qt::AlignmentFlag(int(align_ & Qt::AlignVertical_Mask))) {
	case Qt::AlignBottom: ret.ry() = br.top(); break;
	case Qt::AlignVCenter: ret.ry() = br.center().y(); break;
	case Qt::AlignTop: ret.ry() = br.bottom(); break;
	default: break;
	}
	return ret;
}


void AlignedTextItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) {
	if (isSelected()) {
		painter->setPen(QPen(Qt::DashLine));
		painter->setBrush(Qt::NoBrush);
		painter->drawRect(boundingRect());
	}
}
