#include "VerticalSpacer.h"

#include <algorithm>
#include <numeric>

VerticalSpacer::VerticalSpacer()
    : Widget(),
      mScales()
{

}

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

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

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

void VerticalSpacer::updateChildLocations()
{
    double scaleSum  = std::accumulate(mScales.begin(), mScales.end(), 0.0);
    double offset = 0;
    unsigned delta = mSize.mWidth / unsigned(mChildren.size());
    for(std::size_t idx=0; idx<mChildren.size(); idx++)
    {
        auto& child = mChildren[idx];
        double scale = mScales[idx];
        double delta = mSize.mWidth * (scale/scaleSum);
        child->setBounds(unsigned(delta), mSize.mHeight);
        child->setLocation(DiscretePoint(mLocation.GetX() + unsigned(offset), mLocation.GetY()));
        offset += delta;
    }
}

