#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::AddChildLayers(const PaintEvent* event)
{
    mLayers.clear();
    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()));
        child->OnPaintEvent(event);
        auto layers = child->GetLayers();
        mLayers.insert(mLayers.end(), layers.begin(), layers.end());
        offset += delta;
    }
}

void VerticalSpacer::OnPaintEvent(const PaintEvent* event)
{
    AddChildLayers(event);
}
