#include "tagedit.h"

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

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

void TagEdit::setText(const QString &text)
{
    qDeleteAll(tags);
    tags.clear();

    if(text.isEmpty())
        return;

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

void TagEdit::clearAll()
{
    qDeleteAll(tags);
    tags.clear();
    renderTags();
    outputValue();
    QLineEdit::clear();
}

bool TagEdit::eventFilter(QObject * watched, QEvent * event)
{    
	if (event->type() == QEvent::FocusOut) {
		onEnter();
		//QFocusEvent *focusEvent = static_cast<QFocusEvent *>(event);
		//focusEvent->lostFocus();
		return true;
	}

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

void TagEdit::onEnter()
{
    qDebug() << "onEnter";

    QString str = text().trimmed();
    if(str.isEmpty())
        return;

    addTag(str);
}

void TagEdit::onTagRemoved(Tag* tag)
{    
    tags.removeOne(tag);
    delete tag;

    renderTags();
    outputValue();
}

void TagEdit::addTag(const QString &text)
{
    Tag *tag = new Tag(text, this);
    connect(tag, &Tag::removed, this, &TagEdit::onTagRemoved);
    tags.append(tag);

    clear();

    renderTags();
    outputValue();
}

void TagEdit::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 TagEdit::outputValue()
{
    QStringList value;
    Tag *tag;

    foreach(tag, tags)
    {
        value << tag->text();
    }

    emit tagChanged(value);
}
