/***************************************************************************
 *   Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE support@mankowski.fr  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>  *
 ***************************************************************************/
/** @file
* This file defines classes SKGFlowLayout.
*
* @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgflowlayout.h"
#include "skgdefine.h"

#include <qlayout.h>
#include <qwidget.h>

SKGFlowLayout::SKGFlowLayout(QWidget* iParent, int iMargin, int hSpacing, int vSpacing)
    : QLayout(iParent), m_hSpace(hSpacing), m_vSpace(vSpacing)
{
    setContentsMargins(iMargin, iMargin, iMargin, iMargin);
}

SKGFlowLayout::SKGFlowLayout(int iMargin, int hSpacing, int vSpacing)
    : QLayout(), m_hSpace(hSpacing), m_vSpace(vSpacing)
{
    setContentsMargins(iMargin, iMargin, iMargin, iMargin);
}

SKGFlowLayout::~SKGFlowLayout()
{
    while (count()) {
        QLayoutItem* child = takeAt(0);
        if (child) {
            QWidget* w = child->widget();
            delete w;
            delete child;
        }
    }
}

void SKGFlowLayout::addItem(QLayoutItem* item)
{
    m_itemList.append(item);
}

void SKGFlowLayout::setSpacing(int space)
{
    m_hSpace = space;
    m_vSpace = space;
}

int SKGFlowLayout::horizontalSpacing() const
{
    if (m_hSpace >= 0) {
        return m_hSpace;
    } else {
        return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
    }
}

int SKGFlowLayout::verticalSpacing() const
{
    if (m_vSpace >= 0) {
        return m_vSpace;
    } else {
        return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
    }
}

int SKGFlowLayout::count() const
{
    return m_itemList.size();
}

QLayoutItem* SKGFlowLayout::itemAt(int index) const
{
    return m_itemList.value(index);
}

QLayoutItem* SKGFlowLayout::takeAt(int index)
{
    if (index >= 0 && index < m_itemList.size()) {
        return m_itemList.takeAt(index);
    } else {
        return 0;
    }
}

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

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

int SKGFlowLayout::heightForWidth(int width) const
{
    int height = doLayout(QRect(0, 0, width, 0), true);
    return height;
}

void SKGFlowLayout::setGeometry(const QRect& rect)  // clazy:exclude=function-args-by-value
{
    QLayout::setGeometry(rect);
    doLayout(rect, false);
}

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

QSize SKGFlowLayout::minimumSize() const
{
    QSize size;
    for (auto item : qAsConst(m_itemList)) {
        size = size.expandedTo(item->minimumSize());
    }

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

int SKGFlowLayout::doLayout(const QRect rect, bool testOnly) const
{
    int left, top, right, bottom;
    getContentsMargins(&left, &top, &right, &bottom);
    QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
    int x = effectiveRect.x();
    int y = effectiveRect.y();
    int lineHeight = 0;
    int x1 = x;
    int y1 = y;

    for (auto item : qAsConst(m_itemList)) {
        QWidget* wid = item->widget();
        if (wid) {
            // Get spaces
            int spaceX = horizontalSpacing();
            if (spaceX == -1) {
                spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
            }

            int spaceY = verticalSpacing();
            if (spaceY == -1) {
                spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
            }

            // Try option
            bool optionUsed = false;
            if (lineHeight && x1) {
                int nextX = x1 + item->sizeHint().width() + spaceX;
                if (nextX <= x && y1 - y + item->sizeHint().height() <= lineHeight) {
                    optionUsed = true;

                    // Position item
                    if (!testOnly) {
                        item->setGeometry(QRect(QPoint(x1, y1), item->sizeHint()));
                    }

                    x1 = nextX;
                }
            }

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

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

                x1 = x;
                y1 = y + item->sizeHint().height() + spaceY;
                x = nextX;
                lineHeight = qMax(lineHeight, item->sizeHint().height());
            }
        }
    }
    return y + lineHeight - rect.y() + bottom;
}

int SKGFlowLayout::smartSpacing(QStyle::PixelMetric pm) const
{
    QObject* p = this->parent();
    if (!p) {
        return -1;
    } else if (p->isWidgetType()) {
        QWidget* pw = static_cast<QWidget*>(p);
        return pw->style()->pixelMetric(pm, 0, pw);
    } else {
        return static_cast<QLayout*>(p)->spacing();
    }
}


