#include "iconedlabel.h"

#include "qad_types.h"

#include <QEvent>
#include <QHBoxLayout>
#include <QStyle>


IconedLabel::IconedLabel(QWidget * parent): QFrame(parent) {
	label_.setAlignment(Qt::AlignCenter);
	icon_.setAlignment(Qt::AlignCenter);
	icon_.setScaledContents(true);
	icon_.setHidden(true);
	setIconSize(QSize());
	setDirection(RightToLeft);
}


QString IconedLabel::text() const {
	return label_.text();
}


QIcon IconedLabel::icon() const {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
	return icon_.pixmap(Qt::ReturnByValue).isNull() ? QIcon() : QIcon(icon_.pixmap(Qt::ReturnByValue));
#else
	return icon_.pixmap() == 0 ? QIcon() : QIcon(*icon_.pixmap());
#endif
}


bool IconedLabel::event(QEvent * e) {
	if (e->type() == QEvent::FontChange || e->type() == QEvent::Polish) {
		setIconSize(iconSize());
	}
	return QFrame::event(e);
}


void IconedLabel::checkSpacing() {
	label_.setHidden(label_.text().isEmpty());
	if (!layout()) return;
	if (label_.isHidden() || icon_.isHidden()) {
		layout()->setSpacing(0);
	} else {
		QStyle * s = style();
		if (s) {
			layout()->setSpacing(
				s->layoutSpacing(QSizePolicy::Label, QSizePolicy::Label, dir_ <= Direction::RightToLeft ? Qt::Horizontal : Qt::Vertical));
		}
	}
}


QSize IconedLabel::realIconSize() const {
	return size_.isEmpty() ? preferredIconSize(m_iconSizeAutoScale, this) : size_;
}


void IconedLabel::setText(const QString & t) {
	label_.setText(t);
	checkSpacing();
}


void IconedLabel::setIcon(const QIcon & i) {
	sicon_ = i;
	setIconSize(iconSize());
	icon_.setHidden(icon().isNull());
	checkSpacing();
}


void IconedLabel::setIconSize(const QSize & s) {
	size_    = s;
	QSize sz = realIconSize();
	icon_.setPixmap(sicon_.pixmap(sz));
	icon_.setFixedSize(sz);
}


void IconedLabel::setDirection(IconedLabel::Direction d) {
	dir_ = d;
	if (layout()) {
		delete layout();
	}
	QLayout * lay = new QBoxLayout(static_cast<QBoxLayout::Direction>(dir_));
	lay->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding));
	lay->addWidget(&label_);
	lay->addWidget(&icon_);
	lay->addItem(new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding));
	lay->setContentsMargins(0, 0, 0, 0);
	setLayout(lay);
	checkSpacing();
	updateGeometry();
}


void IconedLabel::setIconSizeAutoScale(double newIconSizeAutoScale) {
	m_iconSizeAutoScale = newIconSizeAutoScale;
	setIconSize(iconSize());
}
