#include "TagEditWidget.h"

#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QDebug>

const QString TagEditWidget::type = "TagEdit";

TagEditWidget::TagEditWidget(QWidget *parent)
    : QLineEdit(parent)
{
	installEventFilter(this);
    connect(this, &QLineEdit::returnPressed, this, &TagEditWidget::onEnter);
}

QVariant TagEditWidget::getValue() const
{
	QStringList value;
	Tag *tag;

	foreach(tag, tags)
	{
		value << tag->text();
	}
	return value.join(",");
}

void TagEditWidget::setValue(const QVariant &value)
{
	qDeleteAll(tags);
	tags.clear();

	if (value.toString().isEmpty())
		return;

	QStringList arr = value.toString().split(",");
	QString item;
	foreach(item, arr)
	{
		Tag *tag = new Tag(item, this);
		connect(tag, &Tag::removed, this, &TagEditWidget::onTagRemoved);
		tags.append(tag);
	}
	renderTags();
	outputValue();
}

bool TagEditWidget::isValueNull() const
{
	return tags.size() <= 0;
}

void TagEditWidget::clearInput()
{
	qDeleteAll(tags);
	tags.clear();
	renderTags();
	outputValue();
    clear();
}

bool TagEditWidget::eventFilter(QObject * watched, QEvent * event)
{    
	if (event->type() == QEvent::FocusOut) {
		onEnter();
		return true;
	}

	return QLineEdit::eventFilter(watched, event);
}

void TagEditWidget::onEnter()
{
    QString str = text().trimmed();
    if(str.isEmpty())
        return;
    addTag(str);
}

void TagEditWidget::onTagRemoved(Tag* tag)
{    
    tags.removeOne(tag);
    delete tag;
    renderTags();
    outputValue();
}

void TagEditWidget::addTag(const QString &text)
{
    Tag *tag = new Tag(text, this);
    connect(tag, &Tag::removed, this, &TagEditWidget::onTagRemoved);
    tags.append(tag);
    QLineEdit::clear();
    renderTags();
    outputValue();
}

void TagEditWidget::renderTags()
{
    quint32 x = 3;
    Tag *tag;
    foreach(tag, tags)
    {
        tag->move(x, 3);
        tag->show();
        x += tag->width() + 5;
    }
    setStyleSheet(QString("padding-left:%1px;").arg(x+3));
}

void TagEditWidget::outputValue()
{
    QStringList value;
    Tag *tag;
    foreach(tag, tags)
        value << tag->text();
    emit tagChanged(value);
}

