package fanch.multijeu.numbers.widget;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class GridLayout extends ViewGroup {

    protected int mGridHeight=4;
    protected int mGridWidth=4;

    protected Rect mChildMargin = new Rect(5,5,5,5);

    public static class LayoutParams extends ViewGroup.LayoutParams {
        public int x=4;
        public int y=4;
        public int marin_top=0;
        public int marin_bottom=0;
        public int marin_left=0;
        public int marin_right=0;

        public LayoutParams() {
            super(1,1);
        }

        public LayoutParams(int _x, int _y) {
            super(1,1);
            x=_x;
            y=_y;
        }

        public LayoutParams(int _x, int _y, int w, int h) {
            super(w,h);
            x=_x;
            y=_y;
        }
    }

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

    public GridLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    public void setGridDimension(int x, int y)
    {
        mGridHeight=y;
        mGridWidth=x;
        requestLayout();
    }

    public int getGridHeight() {
        return mGridHeight;
    }

    public int getGridWidth() {
        return mGridWidth;
    }

    @Override
    protected void onMeasure(int w, int h) {
        setMeasuredDimension(w&MEASURED_SIZE_MASK,
                h&MEASURED_SIZE_MASK);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        final int W = r-l;
        final int H = b-t;
        final int hSize = H/mGridHeight;
        final int wSize = W/mGridWidth;


        for(int i=0; i<count; i++)
        {
            final View child = getChildAt(i);
            final ViewGroup.LayoutParams vglp = child.getLayoutParams();
            if(vglp == null || !(vglp instanceof  LayoutParams)) continue;
            final LayoutParams lp = (LayoutParams) vglp;

            final int x=lp.x;
            final int y=lp.y;
            final int w=lp.width;
            final int h=lp.height;

            setChildFrame(child, x*wSize+lp.marin_left,
                    y*hSize+lp.marin_top,
                    w*wSize-lp.marin_right,
                    h*hSize-lp.marin_bottom);
        }
    }

    private void setChildFrame(View child, int x, int y, int w, int h)
    {
        child.layout(x+mChildMargin.left, y+mChildMargin.top,
                x+w-mChildMargin.right,y+h-mChildMargin.bottom);
    }

}
