package org.cocos2d.extensions.scroll;

import javax.microedition.khronos.opengles.GL10;

import org.cocos2d.CCDirector;
import org.cocos2d.cocoa.CCGeometry.CCPoint;
import org.cocos2d.cocoa.CCGeometry.CCRect;
import org.cocos2d.cocoa.CCGeometry.CCSize;
import org.cocos2d.layers_scenes_transitions_nodes.CCLayer;
import org.cocos2d.support.CCPointExtension;

import android.opengl.GLES20;

public class CCClipNode extends CCLayer {
	public static final int RECT_ORIGIN_INVALID = 99999;
	CCRect _clippedRect = new CCRect();
	
	public CCClipNode(){
		_clippedRect.setRect(RECT_ORIGIN_INVALID + 1, 0, 0, 0);
	}

	static CCPoint pos = CCPoint.Zero;
	static CCPoint pos2 = CCPoint.Zero;
	static CCRect rect = new CCRect();
	
	private /*CGRect*/ void clipRectFromRect(){
		CCSize size = CCDirector.sharedDirector().getWinSizeInPixels();
		
//		CGPoint pos = _clippedRect.origin;
		pos.setPoint(_clippedRect.origin);
		//pos = getParent().convertToWorldSpace(pos.x, pos.y);
		pos = getParent().convertToWorldSpace(pos);
		pos.y = size.height - pos.y;
		pos = CCDirector.sharedDirector().convertToUI(pos);
		
//		CGPoint pos2 = _clippedRect.origin;
		pos2.setPoint(_clippedRect.origin);
		pos2 = CCPointExtension.ccpAdd(pos2, CCPointExtension.ccp(_clippedRect.size.width, _clippedRect.size.height));
//		getParent().convertToWorldSpace(pos2.x, pos2.y, pos2);
		pos2 = getParent().convertToWorldSpace(pos2);
		pos2.y = size.height - pos2.y;
		pos2 = CCDirector.sharedDirector().convertToUI(pos2);
		
		float x1 = Math.min(pos.x, pos2.x);
		float y1 = Math.min(pos.y, pos2.y);
		float x2 = Math.max(pos.x, pos2.x);
		float y2 = Math.max(pos.y, pos2.y);
		
		rect.setRect(x1, y1, x2 - x1, y2 - y1);
		
		//return CGRect.make(x1, y1, x2 - x1, y2 - y1);
	}
	
	@Override
	public void visit() {
		if(_clippedRect.origin.x < RECT_ORIGIN_INVALID){
			/*CGRect globalRect =*/ clipRectFromRect();
			GLES20.glEnable(GLES20.GL_SCISSOR_TEST);
			GLES20.glScissor((int)rect.origin.x, (int)rect.origin.y, (int)rect.size.width, (int)rect.size.height);/*(int)globalRect.origin.x, (int)globalRect.origin.y, 
					(int)globalRect.size.width, (int)globalRect.size.height);*/
		}
		super.visit();
		if(_clippedRect.origin.x < RECT_ORIGIN_INVALID)
			GLES20.glDisable(GLES20.GL_SCISSOR_TEST);
	}
	
	public void setClipRect(CCRect clippedRect) {
		_clippedRect.setRect(clippedRect);
	}
	
}
