package org.cocos2d.actions.tile;

import org.cocos2d.cocoa.CCGeometry.CCPoint;
import org.cocos2d.cocoa.CCGeometry.CCSize;
import org.cocos2d.support.CCPointExtension;
import org.cocos2d.types.ccGridSize;
import org.cocos2d.types.ccQuad3;

////////////////////////////////////////////////////////////

/** CCFadeOutTRTiles action
 Fades out the tiles in a Top-Right direction
 */
public class CCFadeOutTRTiles extends CCTiledGrid3DAction {

	public static CCFadeOutTRTiles action(CCSize gSize, float d) {
		return new CCFadeOutTRTiles(gSize, d);
	}
	
	protected CCFadeOutTRTiles(CCSize gSize, float d) {
		super(gSize, d);
	}
	
    public float testFunc(ccGridSize pos, float time) {
        CCPoint	n = CCPointExtension.ccpMult(CCPointExtension.ccp(gridSize.width,gridSize.height), time);
        if ( (n.x+n.y) == 0.0f )
            return 1.0f;
        return (float)Math.pow( (pos.x+pos.y) / (n.x+n.y), 6 );
    }

    public void turnOnTile(CCPoint pos) {
        setTile(pos, originalTile(pos));
    }

    public void turnOffTile(CCPoint pos) {
        ccQuad3	coords = new ccQuad3();	
        setTile(pos, coords);
    }

    public void transformTile(CCPoint pos, float distance) {
        ccQuad3	coords = originalTile(pos);
        final CCPoint	step = target.getGrid().getStep();

        coords.bl_x += (step.x / 2) * (1.0f - distance);
        coords.bl_y += (step.y / 2) * (1.0f - distance);

        coords.br_x -= (step.x / 2) * (1.0f - distance);
        coords.br_y += (step.y / 2) * (1.0f - distance);

        coords.tl_x += (step.x / 2) * (1.0f - distance);
        coords.tl_y -= (step.y / 2) * (1.0f - distance);

        coords.tr_x -= (step.x / 2) * (1.0f - distance);
        coords.tr_y -= (step.y / 2) * (1.0f - distance);

        setTile(pos, coords);
    }

    @Override
    public void update(float time) {
        int i, j;

        for( i = 0; i < gridSize.width; i++ ) {
            for( j = 0; j < gridSize.height; j++ ) {
                float distance = testFunc(ccGridSize.ccg(i,j), time);
                if ( distance == 0 )
                    turnOffTile(CCPointExtension.ccp(i,j));
                else if ( distance < 1 )
                    transformTile(CCPointExtension.ccp(i,j), distance);
                else
                    turnOnTile(CCPointExtension.ccp(i,j));
            }
        }
    }

}

