package com.tisza.komal.i390;

import android.content.*;
import android.content.res.*;
import android.util.*;
import android.view.*;

public class BoardLayout extends ViewGroup
{
	private static final int strokeWidth = 4;
	
	private int n;
	private float marginRatio;

	public BoardLayout(Context context)
	{
		super(context);
	}

	public BoardLayout(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.BoardLayout);
		marginRatio = ta.getFloat(R.styleable.BoardLayout_marginRatio, 0.1F);
		ta.recycle();
	}

	public void setN(int val)
	{
		n = val;
		forceLayout();
	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		int w = MeasureSpec.getSize(widthMeasureSpec);
		int h = MeasureSpec.getSize(heightMeasureSpec);
		int wMode = MeasureSpec.getMode(widthMeasureSpec);
		int hMode = MeasureSpec.getMode(heightMeasureSpec);
		
		int measureSpecResult;
		
		if (wMode == MeasureSpec.UNSPECIFIED)
		{
			if (hMode == MeasureSpec.UNSPECIFIED)
			{
				measureSpecResult = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
			}
			else
			{
				measureSpecResult = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
			}
		}
		else
		{
			if (hMode == MeasureSpec.UNSPECIFIED)
			{
				measureSpecResult = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY);
			}
			else
			{
				measureSpecResult = MeasureSpec.makeMeasureSpec(Math.min(w, h), MeasureSpec.EXACTLY);
			}
		}
		
		setMeasuredDimension(measureSpecResult, measureSpecResult);
	}

	protected void onLayout(boolean changed, int l, int t, int r, int b)
	{
		if (n == 0) return;
		float size = Math.min(getWidth(), getHeight()) - strokeWidth * 2;
		float tileMargin = size / n * marginRatio;
		float tileSizeWithMargin = (size - (n + 1) * tileMargin) / n + tileMargin;
		for (int i = 0; i < getChildCount(); i++)
		{
			if (i >= n * n) break;
			View v = getChildAt(i);
			if (v == null) continue;
			int x = i % n;
			int y = i / n;
			v.layout((int)(x * tileSizeWithMargin + tileMargin + strokeWidth), (int)(y * tileSizeWithMargin + tileMargin + strokeWidth), (int)((x + 1) * tileSizeWithMargin + strokeWidth), (int)((y + 1) * tileSizeWithMargin + strokeWidth));
		}
	}
}
