#include "clineedit.h"

#include "qad_types.h"

#include <QMouseEvent>
#include <QPainter>


CLineEdit::CLineEdit(QWidget * parent): QLineEdit(parent) {
	cw = new QWidget(this);
	clear_im.load(":/icons/edit-clear-locationbar-rtl.png");
	cw->setCursor(Qt::ArrowCursor);
	cw->setToolTip(tr("Clear"));
	cw->hide();
	cw->installEventFilter(this);
	connect(this, &QLineEdit::textChanged, this, &CLineEdit::textChangedInternal);
	int is     = fontHeight(this);
	QMargins m = textMargins();
	m.setRight(m.right() + (is * 1.2));
	setTextMargins(m);
}


CLineEdit::~CLineEdit() {
	delete cw;
}


void CLineEdit::setReadOnly(bool yes) {
	QLineEdit::setReadOnly(yes);
	textChangedInternal();
}


void CLineEdit::clearClick() {
	if (!isEnabled()) return;
	setText(dt);
	emit cleared();
	emit textEdited(dt);
}


bool CLineEdit::eventFilter(QObject * o, QEvent * e) {
	switch (e->type()) {
	case QEvent::MouseButtonRelease: clearMouseRelease(static_cast<QMouseEvent *>(e)); break;
	case QEvent::Paint: cwPaintEvent(); break;
	default: break;
	}
	return QLineEdit::eventFilter(o, e);
}


void CLineEdit::resizeEvent(QResizeEvent * e) {
	QLineEdit::resizeEvent(e);
	int is = fontHeight(this), tm = (height() - is) / 2;
	cw->setGeometry(width() - is - tm, tm, is, is);
}


void CLineEdit::changeEvent(QEvent * e) {
	QLineEdit::changeEvent(e);
	if (e->type() == QEvent::LanguageChange) {
		cw->setToolTip(tr("Clear"));
		return;
	}
}


void CLineEdit::cwPaintEvent() {
	QPainter p(cw);
	p.setRenderHint(QPainter::SmoothPixmapTransform);
	p.drawImage(cw->rect(), clear_im);
}


void CLineEdit::setDefaultText(const QString & t, bool set_text) {
	dt = t;
	if (set_text) {
		setText(t);
		emit textEdited(t);
		cw->hide();
		return;
	}
	textChangedInternal();
}


void CLineEdit::clearMouseRelease(QMouseEvent * e) {
	if (cw->rect().contains(e->pos())) {
		clearClick();
	}
}


void CLineEdit::textChangedInternal() {
	cw->setVisible((text() != dt) && !isReadOnly());
}
