#include "HorizontalSpacer.h"

#include <algorithm>
#include <numeric>

HorizontalSpacer::HorizontalSpacer()
    : Widget(),
      mScales()
{

}

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

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