package cnp.ew.layout;

import java.util.*;
import java.awt.*;

import cnp.ew.lightweight.*;

public class CpGridLayout implements CpLayoutManager
{
    int rows;
    int columns;
    int hgap;
    int vgap;

    public CpGridLayout(int newRows, int newColumns)
    {
        this(newRows, newColumns, 0, 0);
    }

    public CpGridLayout(int newRows, int newColumns, int newHgap, int newVgap)
    {
        rows = newRows;
        columns = newColumns;
        hgap = newHgap;
        vgap = newVgap;
    }

    public Vector calculateRectsForObjects(CpLightweightComponent c, Vector objects, int x, int y, int width, int height)
    {

    	int numObjects = objects.size();
	    int numRows = rows;
	    int numColumns = columns;
        Vector rects = new Vector(objects.size());

    	if (numObjects == 0) {
    	    return rects;
    	}
    	if (numRows > 0) {
    	    numColumns = (numObjects + numRows - 1) / numRows;
    	} else {
    	    numRows = (numObjects + numColumns - 1) / numColumns;
    	}
    	int w = width;
    	int h = height;
    	w = (w - (numColumns - 1) * hgap) / numColumns;
    	h = (h - (numRows - 1) * vgap) / numRows;

    	for (int tempColumns = 0, newX = x ; tempColumns < numColumns ; tempColumns++, newX += w + hgap) {
    	    for (int tempRows = 0, newY = y ; tempRows < numRows ; tempRows++, newY += h + vgap) {
        		int i = tempRows * numColumns + tempColumns;
        		if (i < numObjects) {
        		    rects.addElement(new Rectangle(newX, newY, w, h));
        		}
    	    }
    	}
    	return rects;
    }

    public Dimension calculatePreferredSizeForObjects(CpLightweightComponent c, Vector objects)
    {

    	int numComponents = objects.size();
    	int nrows = rows;
    	int ncols = columns;

    	if (nrows > 0) {
    	    ncols = (numComponents + nrows - 1) / nrows;
    	} else {
    	    nrows = (numComponents + ncols - 1) / ncols;
    	}
    	int w = 0;
    	int h = 0;
    	for (int i = 0 ; i < numComponents ; i++) {
    	    CpLayoutable layoutable = (CpLayoutable)objects.elementAt(i);
    	    Dimension d = layoutable.preferredSize(c);
    	    if (w < d.width) {
    		    w = d.width;
    	    }
    	    if (h < d.height) {
    		    h = d.height;
    	    }
    	}
	    return new Dimension(
	            ncols * w + (columns-1) * hgap,
			    nrows * h + (rows-1) * vgap);
    }
}
