package org.cocos2d.actions.grid;

import org.cocos2d.CCDirector;
import org.cocos2d.actions.interval.CCIntervalAction;
import org.cocos2d.actions.interval.CCReverseTime;
import org.cocos2d.grid.CCGridBase;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.types.CGSize;

/** Base class for Grid actions */
public abstract class CCGridAction extends CCIntervalAction {
    /** size of the grid */
    protected CGSize gridSize;
    
    public void setGridSize(CGSize gs) {
    	gridSize = new CGSize(gs);
    }
    
    public CGSize getGridSize() {
    	return new CGSize(gridSize);
    }

    /** initializes the action with size and duration */
    protected CCGridAction(CGSize gSize, float d) {
        super(d);
        gridSize = new CGSize(gSize);
    }
    
    @Override
    public void start(CCNode aTarget) {
        super.start(aTarget);

        CCGridBase newgrid = grid();
        CCGridBase targetGrid = target.getGrid();

        // Class<?> clazz = newgrid.getClass();
        if (targetGrid != null && targetGrid.getReuseGrid() > 0) {
            if (targetGrid.isActive() &&
            		targetGrid.getGridWidth() == gridSize.width &&
            		targetGrid.getGridHeight() == gridSize.height &&
            		targetGrid.getClass() == newgrid.getClass()) {
            	targetGrid.reuse(CCDirector.gl);
            } else {
                throw new RuntimeException("Cannot reuse grid_");
            }
        } else {
            if (targetGrid != null && targetGrid.isActive())
                targetGrid.setActive(false);
            
            target.setGrid(newgrid);
            
            if (targetGrid != null)
            	target.getGrid().setActive(true);
        }
    }
    
    /** returns the grid */
    public abstract CCGridBase grid();

    @Override
    public abstract CCGridAction copy();

    @Override
    public CCIntervalAction reverse() {
        return CCReverseTime.action(this);
    }

}
