#include "widgets.h"

#include <QToolBar>
//#include <QStylePainter>


namespace Dict {

class HistButton : public QToolButton
{
public:
	HistButton(QWidget *parent);

protected:
//	void initStyleOption(QStyleOptionToolButton *option ) const;
//	void paintEvent(QPaintEvent *);
	QSize sizeHint() const override;
};

HistButton::HistButton(QWidget *parent)
	: QToolButton(parent)
{}
/*
// hacked to get around button arrow bugs in oxygen
void HistButton::initStyleOption(QStyleOptionToolButton *option ) const
{
	if (!option) return;
	option->initFrom(this);
	option->features = QStyleOptionToolButton::Arrow;
}

// copied from QToolButton because initStyleOption is not virtual
void HistButton::paintEvent(QPaintEvent *)
{
    QStylePainter p(this);
    QStyleOptionToolButton opt;
    initStyleOption(&opt);
    p.drawComplexControl(QStyle::CC_ToolButton, opt);
}
*/
QSize HistButton::sizeHint() const
{
	return QSize(20, 20);
}


History::History(Browser *parent)
	: QWidgetAction(parent), button(0)
{
	browser = parent;
	setMenu(new QMenu(parent));
	connect(menu(), SIGNAL(triggered(QAction *)), SLOT(move(QAction *)));
	connect(menu(), SIGNAL(aboutToShow()), SLOT(set()));
}

void History::move(QAction *action)
{
	browser->moveTo(action->data().toInt());
	emit activated();
}

void History::setEnabled(bool enabled)
{
	QWidgetAction::setEnabled(enabled);
	if (button) button->setEnabled(enabled);
}

void History::set()
{
	menu()->clear();
	QStringList backwardList = browser->backwardList();
	QStringList forwardList = browser->forwardList();
	int backward = backwardList.size();
	int forward = forwardList.size();

	int maxlen = 10;
	if (backward > maxlen/2 && forward > maxlen/2)
		backward = forward = maxlen/2;
	else if (backward > maxlen/2)
		backward = qMin(backward, maxlen - forward);
	else if (forward > maxlen/2)
		forward = qMin(forward, maxlen - backward);

	for (int i = forward; i > 0; --i)
		menu()->addAction(forwardList.at(i - 1))->setData(i);

	QAction *current = menu()->addAction(browser->pageTitle());
	current->setData(0);
	QFont font = current->font();
	font.setBold(true);
	current->setFont(font);

	for (int i = 0; i < backward; ++i)
		menu()->addAction(backwardList.at(i))->setData(-i - 1);
}

QWidget *History::createWidget(QWidget *parent)
{
	if (!qobject_cast<QToolBar *>(parent))
		return QWidgetAction::createWidget(parent);

	button = new HistButton(parent);
// 	button->setArrowType(Qt::DownArrow);
	button->setMenu(menu());
	button->setPopupMode(QToolButton::MenuButtonPopup);
	button->setEnabled(!browser->pageTitle().isEmpty());
	button->setToolTip(text().remove('&'));

	connect(button, SIGNAL(pressed()), button, SLOT(showMenu()));

	return button;
}

void History::deleteWidget(QWidget *)
{
	delete button;
	button = 0;
}

}
