/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "flowlayout.h"
#include <QWidget>

namespace LeechCraft
{
namespace Util
{
	FlowLayout::FlowLayout (QWidget *parent,
			int margin, int hspace, int vspace)
	: QLayout { parent }
	, HSpace_ { hspace }
	, VSpace_ { vspace }
	{
		setContentsMargins (margin, margin, margin, margin);
	}

	FlowLayout::FlowLayout (int margin, int hspace, int vspace)
	: FlowLayout { nullptr, margin, hspace, vspace }
	{
	}

	FlowLayout::~FlowLayout ()
	{
		while (const auto item = takeAt (0))
			delete item;
	}

	void FlowLayout::addItem (QLayoutItem *item)
	{
		ItemList_ << item;
	}

	int FlowLayout::horizontalSpacing () const
	{
		return HSpace_ >= 0 ?
				HSpace_ :
				SmartSpacing (QStyle::PM_LayoutHorizontalSpacing);
	}

	int FlowLayout::verticalSpacing () const
	{
		return VSpace_ >= 0 ?
				VSpace_ :
				SmartSpacing (QStyle::PM_LayoutVerticalSpacing);
	}

	Qt::Orientations FlowLayout::expandingDirections () const
	{
		return 0;
	}

	bool FlowLayout::hasHeightForWidth () const
	{
		return true;
	}

	int FlowLayout::heightForWidth (int width) const
	{
		return DoLayout ({ 0, 0, width, 0 }, true);
	}

	int FlowLayout::count () const
	{
		return ItemList_.size ();
	}

	QLayoutItem* FlowLayout::itemAt (int idx) const
	{
		return ItemList_.value (idx);
	}

	QLayoutItem* FlowLayout::takeAt (int idx)
	{
		if (idx >= 0 && idx < ItemList_.size ())
			return ItemList_.takeAt (idx);
		else
			return nullptr;
	}

	QSize FlowLayout::minimumSize () const
	{
		QSize size;
		for (const auto item : ItemList_)
			size = size.expandedTo (item->minimumSize ());

		size += QSize { margin () * 2, margin () * 2 };
		return size;
	}

	void FlowLayout::setGeometry (const QRect& rect)
	{
		QLayout::setGeometry (rect);
		DoLayout (rect, false);
	}

	QSize FlowLayout::sizeHint () const
	{
		return minimumSize ();
	}

	int FlowLayout::DoLayout (const QRect& rect, bool testOnly) const
	{
		int left = 0, top = 0, right = 0, bottom = 0;
		getContentsMargins (&left, &top, &right, &bottom);

		const auto& effectiveRect = rect.adjusted (left, top, -right, -bottom);
		int x = effectiveRect.x ();
		int y = effectiveRect.y ();
		int lineHeight = 0;

		for (const auto item : ItemList_)
		{
			const auto widget = item->widget ();

			int spaceX = horizontalSpacing ();
			if (spaceX == -1)
				spaceX = widget->style ()->layoutSpacing (QSizePolicy::PushButton,
						QSizePolicy::PushButton, Qt::Horizontal);
			int spaceY = verticalSpacing ();
			if (spaceY == -1)
				spaceY = widget->style ()->layoutSpacing (QSizePolicy::PushButton,
						QSizePolicy::PushButton, Qt::Vertical);

			const auto& sizeHint = item->sizeHint ();
			const int hintWidth = sizeHint.width ();
			int nextX = x + hintWidth + spaceX;
			if (nextX - spaceX > effectiveRect.right () &&
					lineHeight > 0)
			{
				x = effectiveRect.x ();
				y += lineHeight + spaceY;
				nextX = x + hintWidth + spaceX;
				lineHeight = 0;
			}

			if (!testOnly)
				item->setGeometry ({ { x, y }, sizeHint });

			x = nextX;
			lineHeight = std::max (lineHeight, sizeHint.height ());
		}

		return y + lineHeight - rect.y () + bottom;
	}

	int FlowLayout::SmartSpacing (QStyle::PixelMetric pm) const
	{
		const auto obj = parent ();
		if (!obj)
			return -1;
		else if (obj->isWidgetType ())
		{
			const auto pw = static_cast<QWidget*> (obj);
			return pw->style ()->pixelMetric (pm, 0, pw);
		}
		else
			return static_cast<QLayout*> (obj)->spacing ();
	}
}
}
