package tetris;

import java.awt.Point;
import java.util.*;

public class TetrisPiece {
    // The block which should be used to paint this piece.
    private TetrisBlock block;	

    // List of offsets from (0,0) where blocks of this piece lie.
    private List offsets;

    // Size of the bounding box square around this piece.
    private int pieceSize;

    /** Construct a new TetrisPiece */
    private TetrisPiece(TetrisBlock block, List offsets, int pieceSize) {
	this.block = block;
	this.offsets = offsets;
	this.pieceSize = pieceSize;
    }

    /** Construct a new TetrisPiece given a block, point offsets
     *  and piece bounding box size.
     **/
    public TetrisPiece(TetrisBlock block, Point[] offsets, int pieceSize) {
	this.block = block;
	this.offsets = new ArrayList();
	for (int i=0; i<offsets.length; i++)
	    this.offsets.add(offsets[i]);
	this.pieceSize = pieceSize;
    }

    /** @returns this.block */
    public TetrisBlock getBlock() {
	return block;
    }

    /** @returns An iterator over this.offsets */
    public Iterator getOffsets() {
	return offsets.iterator();
    }

    /** @returns A new TetrisPiece rotated 90 degrees */
    public TetrisPiece rotate() {
	List newOffsets = new ArrayList();
	Iterator i = getOffsets();
	double rotC = -0.5 + 0.5 * (double) pieceSize;

	while (i.hasNext()) {
	    Point o = (Point) i.next();

	    double offX = -rotC + o.getX();
	    double offY = -rotC + o.getY();
	    int newX = (int) (rotC + offY);
	    int newY = (int) (rotC - offX);

	    newOffsets.add(new Point(newX, newY));
	}

	return new TetrisPiece(block, newOffsets, pieceSize);
    }
}
