#include "stateicon.h"

#include "qad_types.h"

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


StateIcon::StateIcon(QWidget * parent): IconedLabel(parent) {}


QString StateIcon::saveStates() const {
	return QString::fromLatin1(qSerialize(src_states).toBase64());
}


void StateIcon::loadStates(const QString & ba) {
	src_states = qDeserialize<QMap<int, QPair<QString, QString>>>(QByteArray::fromBase64(ba.toLatin1()));
	prepare();
}


void StateIcon::clearStates() {
	src_states.clear();
	prepare();
}


void StateIcon::addState(int st, QString text, QIcon icon) {
	src_states[st]      = QPair<QString, QString>(text, "");
	prepared_states[st] = QPair<QString, QIcon>(text, icon);
	setState(m_state);
}


void StateIcon::addState(int st, QString text, QString icon_path) {
	src_states[st]      = QPair<QString, QString>(text, icon_path);
	prepared_states[st] = QPair<QString, QIcon>(text, QIcon(icon_path));
	setState(m_state);
}


QList<int> StateIcon::allStates() const {
	return src_states.keys();
}


QString StateIcon::stateText(int st) const {
	return src_states.value(st).first;
}


QString StateIcon::stateIcon(int st) const {
	return src_states.value(st).second;
}


void StateIcon::prepare() {
	prepared_states.clear();
	QMapIterator<int, QPair<QString, QString>> it(src_states);
	while (it.hasNext()) {
		it.next();
		auto & ps(prepared_states[it.key()]);
		ps.first  = it.value().first;
		ps.second = QIcon(it.value().second);
	}
	setState(m_state);
}


void StateIcon::setState(int newState) {
	m_state = newState;
	auto cv = prepared_states.value(m_state);
	if (m_changeText) setText(cv.first);
	if (m_changeIcon) setIcon(cv.second);
}


void StateIcon::setChangeIcon(bool newChangeIcon) {
	m_changeIcon = newChangeIcon;
}


void StateIcon::setChangeText(bool newChangeText) {
	m_changeText = newChangeText;
}
