package org.cocos2d.actions.grid;

import org.cocos2d.CCDirector;
import org.cocos2d.actions.interval.CCIntervalAction;
import org.cocos2d.actions.interval.CCReverseTime;
import org.cocos2d.base_nodes.CCNode;
import org.cocos2d.cocoa.CCGeometry.CCSize;
import org.cocos2d.grid.CCGridBase;

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

    /** initializes the action with size and duration */
    protected CCGridAction(CCSize gSize, float d) {
        super(d);
        gridSize = new CCSize(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();
            } 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);
    }

}
