module gedo.gui.table;



private import gedo.gui.component;
private import gedo.video.rect;
private import gedo.video.color;



public class Table : Component
{
public:
	this(int colCount, int rowCount)
	{
		_rows.length = rowCount;
		foreach(inout row; _rows)
		{
			row = new RowItem(colCount);
			add(row);
		}
	}


	void set(int x, int y, Component item)
	{
		_rows[y].items[x] = item;
	}


	RowItem[] rows()
	{
		return _rows;
	}


	void fill(Color c)
	{
		_fillColor = c;
	}


	void frame(Color c)
	{
		_frameColor = c;
	}


	override void onUpdate()
	{
		if(_rows.length > 0)
		{
			for(auto i=0; i<_rows[0].items.length; ++i)
			{
				auto width = 0.0f;
				foreach(row; _rows)
				{
					if(row.items[i].size[0] > width)
					{
						width = row.items[i].size[0];
					}
				}

				foreach(row; _rows)
				{
					row.widths[i] = width;
				}
			}

			foreach(row; _rows)
			{
				row.alignItems();
			}

			Component.alignVertical(_rows, [0.0f, 0.0f]);

			size[0] = _rows[0].size[0] + 4.0;

			float miny = _rows[length-1].position[1] - _rows[length-1].size[1]*0.5 - 2.0;
			float maxy = _rows[0].position[1] + _rows[0].size[1]*0.5 + 2.0;

			size[1] = maxy - miny;
		}
		else
		{
			size[] = 0.0;
		}
	}


	override void onDraw()
	{
		auto rect = Rect([0.0f, 0.0f], size);

		if(_fillColor != 0)
		{
			rect.fill(_fillColor);
		}

		if(_frameColor != 0)
		{
			rect.frame(2.0, _frameColor);
		}
	}


private:
	RowItem[] _rows;
	Color     _fillColor = rgba(0, 0, 0, 128);
	Color     _frameColor = WHITE;
}



public class RowItem : Component
{
public:
	this(int count)
	{
		_items.length  = count;
		_widths.length = count;
	}


	float width()
	{
		float sum = 0.0;

		foreach(w; _widths)
		{
			sum += w + 4.0;
		}

		return sum;
	}


	float height()
	{
		float max = 0.0;
		foreach(item; _items)
		{
			if(item.size[1] > max)
			{
				max = item.size[1];
			}
		}

		return max;
	}


	Component[] items()
	{
		return _items;
	}


	float[] widths()
	{
		return _widths;
	}


	void alignItems()
	{
		size[0] = width;
		size[1] = height;

		float x = -size[0]*0.5;

		foreach(i, item; _items)
		{
			x += _widths[i] * 0.5 + 2.0;

			item.position[0] = x;
			item.position[1] = 0.0;

			x += _widths[i] * 0.5 + 2.0;
		}
	}


	override void onUpdate()
	{
		foreach(item; _items)
		{
			item.update();
		}
	}


	override void onDraw()
	{
		foreach(item; _items)
		{
			item.drawRecursive();
		}
	}


	override bool onAxisMove(int axis)
	{
		bool result = false;
		foreach(item; _items)
		{
			result |= item.onAxisMove(axis);
		}

		return result;
	}


	override bool onClick()
	{
		bool result = false;
		foreach(item; _items)
		{
			result |= item.click();
		}

		return result;
	}


private:
	Component[] _items;
	float[]     _widths;
}
