/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Ricardo Quesada
Copyright (c) 2011      Zynga Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2d.shaders;

import java.nio.IntBuffer;

import org.cocos2d.include.ccConfig;
import org.cocos2d.include.ccMacros;
import org.cocos2d.kazmath.GL.Matrix;

import android.opengl.GLES20;

/**
 * @addtogroup shaders
 * @{
 */

public class ccGLStateCache {

	/** vertex attrib flags */
	public static final int kCCVertexAttribFlag_None		= 0;
	public static final int kCCVertexAttribFlag_Position	= 1 << 0;
	public static final int kCCVertexAttribFlag_Color		= 1 << 1;
	public static final int kCCVertexAttribFlag_TexCoords	= 1 << 2;
	public static final int kCCVertexAttribFlag_PosColorTex	= ( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_Color | kCCVertexAttribFlag_TexCoords );

	/** GL server side states */
	public enum ccGLServerState {
//		CC_GL_SCISSOR_TEST = 1 << 0,
//		CC_GL_STENCIL_TEST = 1 << 1,
//		CC_GL_DEPTH_TEST = 1 << 2,
//		CC_GL_BLEND = 1 << 3,
//		CC_GL_DITHER = 1 << 4,

//		CC_GL_ALL = ( CC_GL_SCISSOR_TEST | CC_GL_STENCIL_TEST | CC_GL_DEPTH_TEST | CC_GL_BLEND | CC_GL_DITHER ),
//		CC_GL_ALL = ( CC_GL_BLEND ),
		CC_GL_ALL
	}

	/** Invalidates the GL state cache.
	 If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache.
	 @since v2.0.0
	 */
	public static void ccGLInvalidateStateCache() {
		Matrix.kmGLFreeAll();

		s_uCurrentProjectionMatrix = -1;
		s_bVertexAttribPosition = false;
		s_bVertexAttribColor = false;
		s_bVertexAttribTexCoords = false;

		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			s_uCurrentShaderProgram = -1;
			for(int i = 0;i < kCCMaxActiveTexture;i++) {
				s_uCurrentBoundTexture[i] = -1;
			}

			s_eBlendingSource = -1;
			s_eBlendingDest = -1;
			s_eGLServerState = 0;
		}
	}

	/** Uses the GL program in case program is different than the current one.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly.
	 @since v2.0.0
	 */
	public static void ccGLUseProgram(int program) {
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			if( program != s_uCurrentShaderProgram ) {
				s_uCurrentShaderProgram = program;
			}
		} // CC_ENABLE_GL_STATE_CACHE

		GLES20.glUseProgram(program);
	}

	/** Deletes the GL program. If it is the one that is being used, it invalidates it.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly.
	 @since v2.0.0
	 */
	public static void ccGLDeleteProgram(int program) {
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			if(program == s_uCurrentShaderProgram) {
				s_uCurrentShaderProgram = -1;
			}
		} // CC_ENABLE_GL_STATE_CACHE

		GLES20.glDeleteProgram( program );
	}

	/** Uses a blending function in case it not already used.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly.
	 @since v2.0.0
	 */
	public static void ccGLBlendFunc(int sfactor, int dfactor) {
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			if (sfactor != s_eBlendingSource || dfactor != s_eBlendingDest) {
				s_eBlendingSource = sfactor;
				s_eBlendingDest = dfactor;
			}
		} // CC_ENABLE_GL_STATE_CACHE

		SetBlending(sfactor, dfactor);
	}

	/** Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD.
	 @since v2.0.0
	 */
	public static void ccGLBlendResetToCache() {
		GLES20.glBlendEquation(GLES20.GL_FUNC_ADD);
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			SetBlending(s_eBlendingSource, s_eBlendingDest);
		} else {
			SetBlending(ccConfig.CC_BLEND_SRC, ccConfig.CC_BLEND_DST);
		} // CC_ENABLE_GL_STATE_CACHE
	}

	/** sets the projection matrix as dirty
	 @since v2.0.0
	 */
	public static void ccSetProjectionMatrixDirty() {
		s_uCurrentProjectionMatrix = -1;
	}

	/** Will enable the vertex attribs that are passed as flags.
	 Possible flags:

		* kCCVertexAttribFlag_Position
		* kCCVertexAttribFlag_Color
		* kCCVertexAttribFlag_TexCoords

	 These flags can be ORed. The flags that are not present, will be disabled.

	 @since v2.0.0
	 */
	public static void ccGLEnableVertexAttribs(int flags) {
		ccGLBindVAO(0);

		/* Position */
		boolean enablePosition = (flags & kCCVertexAttribFlag_Position) != 0 ? true : false;

		if (enablePosition != s_bVertexAttribPosition) {
			if (enablePosition) {
				GLES20.glEnableVertexAttribArray(CCGLProgram.kCCVertexAttrib_Position);
			} else {
				GLES20.glDisableVertexAttribArray(CCGLProgram.kCCVertexAttrib_Position);
			}

			s_bVertexAttribPosition = enablePosition;
		}

		/* Color */
		boolean enableColor = (flags & kCCVertexAttribFlag_Color) != 0 ? true : false;

		if (enableColor != s_bVertexAttribColor) {
			if (enableColor) {
				GLES20.glEnableVertexAttribArray(CCGLProgram.kCCVertexAttrib_Color);
			} else {
				GLES20.glDisableVertexAttribArray(CCGLProgram.kCCVertexAttrib_Color);
			}

			s_bVertexAttribColor = enableColor;
		}

		/* Tex Coords */
		boolean enableTexCoords = (flags & kCCVertexAttribFlag_TexCoords) != 0 ? true : false;

		if (enableTexCoords != s_bVertexAttribTexCoords) {
			if (enableTexCoords) {
				GLES20.glEnableVertexAttribArray(CCGLProgram.kCCVertexAttrib_TexCoords);
			} else {
				GLES20.glDisableVertexAttribArray(CCGLProgram.kCCVertexAttrib_TexCoords);
			}

			s_bVertexAttribTexCoords = enableTexCoords;
		}
	}

	/** If the texture is not already bound to texture unit 0, it binds it.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
	 @since v2.0.0
	 */
	public static void ccGLBindTexture2D(int textureId) {
		ccGLBindTexture2DN(0, textureId);
	}

	/** If the texture is not already bound to a given unit, it binds it.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
	 @since v2.1.0
	 */
	public static void ccGLBindTexture2DN(int textureUnit, int textureId) {
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			ccMacros.CCAssert(textureUnit < kCCMaxActiveTexture, "textureUnit is too big");
			if (s_uCurrentBoundTexture[textureUnit] != textureId) {
				s_uCurrentBoundTexture[textureUnit] = textureId;
				GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + textureUnit);
				GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
			}
		} else {
			GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + textureUnit);
			GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
		}
	}

	/** It will delete a given texture. If the texture was bound, it will invalidate the cached.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
	 @since v2.0.0
	 */
	public static void ccGLDeleteTexture(int textureId) {
		ccGLDeleteTextureN(0, textureId);
	}

	/** It will delete a given texture. If the texture was bound, it will invalidate the cached for the given texture unit.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
	 @since v2.1.0
	 */
	public static void ccGLDeleteTextureN(int textureUnit, int textureId) {
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
			if (s_uCurrentBoundTexture[textureUnit] == textureId) {
				s_uCurrentBoundTexture[textureUnit] = -1;
			}
		} // CC_ENABLE_GL_STATE_CACHE

		IntBuffer textures = IntBuffer.allocate(1);
		textures.put(0, textureId);
		GLES20.glDeleteTextures(1, textures);
	}

	/** If the vertex array is not already bound, it binds it.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly.
	 @since v2.0.0
	 */
	public static void ccGLBindVAO(int vaoId) {
		if(ccConfig.CC_TEXTURE_ATLAS_USE_VAO != 0) {
			if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {
				if (s_uVAO != vaoId) {
					s_uVAO = vaoId;
// TODO					GLES20.glBindVertexArray(vaoId);
				}
			} else {
// TODO				GLES20.glBindVertexArray(vaoId);
			} // CC_ENABLE_GL_STATE_CACHE
		}
	}

	/** It will enable / disable the server side GL states.
	 If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly.
	 @since v2.0.0
	 */
	public static void ccGLEnable( ccGLServerState flags ) {
		if(ccConfig.CC_ENABLE_GL_STATE_CACHE != 0) {

//			int enabled = 0;
//
//			/* GL_BLEND */
//			if( (enabled = (flags & CC_GL_BLEND)) != (s_eGLServerState & CC_GL_BLEND) ) {
//				if( enabled ) {
//					glEnable( GL_BLEND );
//					s_eGLServerState |= CC_GL_BLEND;
//				} else {
//					glDisable( GL_BLEND );
//					s_eGLServerState &=  ~CC_GL_BLEND;
//				}
//			}

		} else {
//			if( flags & CC_GL_BLEND ) {
//				glEnable( GL_BLEND );
//			} else {
//				glDisable( GL_BLEND );
//			}
		}
	}

	private static int			s_uCurrentProjectionMatrix = -1;
	private static boolean		s_bVertexAttribPosition = false;
	private static boolean		s_bVertexAttribColor = false;
	private static boolean		s_bVertexAttribTexCoords = false;

	// #if CC_ENABLE_GL_STATE_CACHE

	private static final int kCCMaxActiveTexture = 16;

	private static int		s_uCurrentShaderProgram = -1;
	private static int []	s_uCurrentBoundTexture = { -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, };
	private static int		s_eBlendingSource = -1;
	private static int		s_eBlendingDest = -1;
	private static int		s_eGLServerState = 0;
	// #if CC_TEXTURE_ATLAS_USE_VAO
	private static int		s_uVAO = 0;
	// #endif

	// #endif // CC_ENABLE_GL_STATE_CACHE

	private static void SetBlending(int sfactor, int dfactor) {
		if (sfactor == GLES20.GL_ONE && dfactor == GLES20.GL_ZERO) {
			GLES20.glDisable(GLES20.GL_BLEND);
		} else {
			GLES20.glEnable(GLES20.GL_BLEND);
			GLES20.glBlendFunc(sfactor, dfactor);
		}
	}
}

// end of shaders group
/// @}
