/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "widget_sizer.h"

		using namespace GS;
		using namespace GS::S2D;


//------------------------------------------------------------------------------
Widget				*SizerWidget::Add(Widget *widget)
{
	if	(widget)
		widget->SetParent(this);
	return widget;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
void				SizerWidget::Invalidate()
{
	ListForeachPtr(Widget *, c, children)
		c->Invalidate();
	Widget::Invalidate();
}
void				HSizerWidget::Refresh()
{
	ListForeachPtr(Widget *, c, children)
	{
		c->Refresh();
		if	(c->IsDirty())
			dirty = true;
	}
}
void				HSizerWidget::Compose(Picture &output, const iRect &out_rect)
{
	if	(hidden || !dirty || !children.GetCount())
		return;

	rect = out_rect;
	rect.sy += (int)border_size.x;
	rect.ey -= (int)border_size.y;
	rect.sx += (int)border_size.z;
	rect.ex -= (int)border_size.w;

	iRect wid_rect(rect);

	float tsz = 0.f;
	ListForeachPtr(Widget *, c, children)
		if	(!c->IsHidden())
			tsz += c->GetFormat().x;

	float stx = (float)out_rect.GetWidth() / tsz;
	ListForeachPtr(Widget *, c, children)
		if	(!c->IsHidden())
		{
			float cell_size = stx * c->GetFormat().x;
			wid_rect.ex = wid_rect.sx + (int)cell_size;
			c->Compose(output, wid_rect);
			wid_rect.sx += (int)cell_size;
		}
		else
			c->Validate();

	dirty = false;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
void				VSizerWidget::Refresh()
{
	ListForeachPtr(Widget *, c, children)
	{
		c->Refresh();
		if	(c->IsDirty())
			dirty = true;
	}
}
void				VSizerWidget::Compose(Picture &output, const iRect &out_rect)
{
	if	(hidden || !dirty || !children.GetCount())
		return;

	rect = out_rect;
	rect.sy += (int)border_size.x;
	rect.ey -= (int)border_size.y;
	rect.sx += (int)border_size.z;
	rect.ex -= (int)border_size.w;

	iRect wid_rect(rect);

	float tsy = 0.f;
	ListForeachPtr(Widget *, c, children)
		if	(!c->IsHidden())
			tsy += c->GetFormat().y;

	float sty = (float)out_rect.GetHeight() / tsy;
	ListForeachPtr(Widget *, c, children)
		if	(!c->IsHidden())
		{
			float cell_size = sty * c->GetFormat().y;
			wid_rect.ey = wid_rect.sy + (int)cell_size;
			c->Compose(output, wid_rect);
			wid_rect.sy += (int)cell_size;
		}
		else
			c->Validate();

	dirty = false;
}
//------------------------------------------------------------------------------
