#include "widgets.h"

#include <QIcon>
#include <QPixmap>
#include <QStyle>


namespace Dict {

Status::Status(QWidget *parent)
	: QWidget(parent)
{
	picture = new QLabel(this);
	label = new QLabel(this);
	QLayout *layout = new QHBoxLayout(this);
	layout->addWidget(picture);
	layout->addWidget(label);
	layout->setContentsMargins(4, 0, 10, 0);
}

void Status::setStatus(const QString &icon, const QString &text, bool enabled)
{
	QPixmap pix = QIcon::fromTheme(icon).pixmap(
		style()->pixelMetric(QStyle::PM_ToolBarIconSize),
		(enabled) ? QIcon::Normal : QIcon::Disabled);
	picture->setPixmap(pix);
	label->setText(text);
}

void Status::setTip(const QString &text)
{
	picture->setToolTip(text);
}


Progress::Progress(QWidget *parent)
	: QProgressBar(parent)
{
	setMaximumSize(100, 16);
	setFormat("");
	hide();

	timer.setInterval(1000);
	timer.setSingleShot(true);
	connect(&timer, SIGNAL(timeout()), SLOT(hide()));
}

void Progress::set(int current, int total)
{
	if (!current) {
		timer.stop();
		setRange(0, total);
		show();
	}
	setValue(current);
	if (current == total)
		timer.start();
}


Statusbar::Statusbar(QWidget *parent)
	: QStatusBar(parent)
{
	progress = new Progress(this);
	addPermanentWidget(progress);

	host = new Status(this);
	addPermanentWidget(host);

	user = 0;
}

void Statusbar::showMessage(const QUrl &url)
{
	QString message = url.url();
	QStatusBar::showMessage(message, (message.endsWith("...")) ? 0 : 4000);
}

void Statusbar::setHost(bool connected, const QString &hostname)
{
	host->setStatus("network-workgroup", hostname, connected);
	host->setTip((connected) ? i18n("Connected") : i18n("Disconnected"));
}

void Statusbar::setUser(bool authenticated, const QString &username)
{
	if (authenticated) {
		if (!user)
			user = new Status(this);
		if (user->isVisible())
			return;
		user->setStatus("user-identity", username, authenticated);
		user->setTip(i18n("User"));
		addPermanentWidget(user);
		addPermanentWidget(host);
		user->show();
	} else if (user)
		removeWidget(user);
}

}
