#include "messageitem.h"

#include <QTimer>
#include <QSoundEffect>

MessageItem::MessageItem(uint32_t itemIdIn, QString name, uint8_t value,  QObject *parent):
	Item(itemIdIn, name, value, parent)
{
	alertSound.setVolume(1.0);
	type_ = ITEM_VALUE_NO_VALUE;
}

MessageItem::MessageItem(const ItemData& itemData,  QObject *parent):
	Item(itemData, parent)
{
	alertSound.setVolume(1.0);
}

MessageItem::~MessageItem()
{
	closeMessageBox();
}

void MessageItem::enactValue(uint8_t value)
{
	if(value && !messageBox_)
	{
		if(!alertSoundFileName.isEmpty())
			alertSound.play();
		messageBox_ = new QMessageBox(QMessageBox::NoIcon, name_, message_);
		messageBox_->setModal(false);
		connect(messageBox_, &QMessageBox::finished, this, &MessageItem::closeMessageBox);
		messageBox_->show();
	}
	else if(!value && messageBox_)
	{
		closeMessageBox();
	}
}


void MessageItem::closeMessageBox()
{
	if(messageBox_)
	{
		value_ = 0;
		messageBox_->hide();
		delete messageBox_;
		messageBox_ = nullptr;
	}
}

QString MessageItem::getAlert()
{
	return alertSoundFileName;
}

void MessageItem::setAlert(const QString &in)
{
	alertSoundFileName = in;
	alertSound.setSource(QUrl::fromLocalFile(alertSoundFileName));
}

void MessageItem::setMessage(const QString& in)
{
	message_ = in;
}

QString MessageItem::getMessage()
{
	return message_;
}

void MessageItem::store(QJsonObject &json)
{
	json["Type"] = "Message";
	Item::store(json);
	json["Message"] = message_;
	if(!alertSoundFileName.isEmpty())
		json["Alert"] = alertSoundFileName;
}

void MessageItem::load(const QJsonObject &json, const bool preserve)
{
	Item::load(json,preserve);
	message_ = json["Message"].toString("Invalid Message");
	alertSoundFileName = json["Alert"].toString("");
	if(!alertSoundFileName.isEmpty())
		alertSound.setSource(QUrl::fromLocalFile(alertSoundFileName));
}
