#include "HorizontalSpacer.h"

#include <algorithm>
#include <numeric>
#include <iostream>

HorizontalSpacer::HorizontalSpacer()
    : Widget(),
      mScales()
{
    mName = "HorizontalSpacer";
}

std::unique_ptr<HorizontalSpacer> HorizontalSpacer::Create()
{
    return std::make_unique<HorizontalSpacer>();
}

void HorizontalSpacer::addWidget(WidgetUPtr widget)
{
    addWidgetWithScale(std::move(widget), 1.0);
}

void HorizontalSpacer::addWidgetWithScale(WidgetUPtr widget, double scale)
{
    Widget::addWidget(std::move(widget));
    mScales.push_back(scale);
}

void HorizontalSpacer::updateChildLocations()
{
    double scaleSum  = std::accumulate(mScales.begin(), mScales.end(), 0.0);
    double offset = 0;
    double height = mSize.mHeight;
    if (mSize.mMaxHeight > 0 && height > mSize.mMaxHeight)
    {
        height = mSize.mMaxHeight;
    }

    for(std::size_t idx=0; idx<mChildren.size(); idx++)
    {
        auto& child = mChildren[idx];
        double scale = mScales[idx];
        double delta = height * (scale/scaleSum);
        auto size = child->getSize();
        if (size.mMaxHeight > 0 && delta > size.mMaxHeight)
        {
            delta = size.mMaxHeight;
        }
        child->setBounds(mSize.mWidth, unsigned(delta));
        child->setLocation(DiscretePoint(mLocation.getX(), mLocation.getY() + unsigned(offset)));
        offset += delta;
    }
}
