/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 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.label_nodes;

import org.cocos2d.CCDirector;
import org.cocos2d.base_nodes.CCAtlasNode;
import org.cocos2d.cocoa.CCGeometry.CCPoint;
import org.cocos2d.cocoa.CCGeometry.CCSize;
import org.cocos2d.include.CCProtocols.CCLabelProtocol;
import org.cocos2d.include.ccConfig;
import org.cocos2d.include.ccMacros;
import org.cocos2d.include.ccTypes.ccColor4B;
import org.cocos2d.include.ccTypes.ccV3F_C4B_T2F_Quad;
import org.cocos2d.opengl.CCDrawingPrimitives;
import org.cocos2d.support.CCPointExtension;
import org.cocos2d.textures.CCTexture2D;
import org.cocos2d.textures.CCTextureCache;

/**
 * @addtogroup GUI
 * @{
 * @addtogroup label
 * @{
 */

/** @brief CCLabelAtlas is a subclass of CCAtlasNode.
 * 
 * It can be as a replacement of CCLabel since it is MUCH faster.
 * 
 * CCLabelAtlas versus CCLabel:
 * - CCLabelAtlas is MUCH faster than CCLabel
 * - CCLabelAtlas "characters" have a fixed height and width
 * - CCLabelAtlas "characters" can be anything you want since they are taken from an image file
 * 
 * A more flexible class is CCLabelBMFont. It supports variable width characters and it also has a nice editor.
 */
public class CCLabelAtlas extends CCAtlasNode implements CCLabelProtocol {

	public CCLabelAtlas() {
	}

	/** creates the CCLabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */
	public static CCLabelAtlas create(final String string, final String charMapFile, int itemWidth, int itemHeight, int startCharMap) {
		CCLabelAtlas pRet = new CCLabelAtlas();
		if(pRet != null && pRet.initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) {
			return pRet;
		}
		pRet = null;
		return null;
	}

	/** creates the CCLabelAtlas with a string and a configuration file
	 * @since v2.0
	 */
	public static CCLabelAtlas create(final String string, final String fntFile) {
		CCLabelAtlas ret = new CCLabelAtlas();
		if (ret != null) {
			if (ret.initWithString(string, fntFile))
			{
			} else {
				ret = null;
			}
		}

		return ret;
	}

	/** initializes the CCLabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas */
	public boolean initWithString(final String string, final String charMapFile, int itemWidth, int itemHeight, int startCharMap) {
		CCTexture2D texture = CCTextureCache.sharedTextureCache().addImage(charMapFile);
		return initWithString(string, texture, itemWidth, itemHeight, startCharMap);
	}

	/** initializes the CCLabelAtlas with a string and a configuration file
	 * @since v2.0
	 */
	public boolean initWithString(final String string, final String fntFile) {
/* TODO
		String pathStr = CCFileUtils.sharedFileUtils().fullPathForFilename(fntFile);
		String relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/";
		CCDictionary dict = CCDictionary.createWithContentsOfFile(pathStr.c_str());

		ccMacros.CCAssert(((CCString*)dict->objectForKey("version"))->intValue() == 1, "Unsupported version. Upgrade cocos2d version");

		std::string texturePathStr = relPathStr + ((CCString*)dict->objectForKey("textureFilename"))->getCString();
		CCString *textureFilename = CCString::create(texturePathStr);
		unsigned int width = ((CCString*)dict->objectForKey("itemWidth"))->intValue() / CC_CONTENT_SCALE_FACTOR();
		unsigned int height = ((CCString*)dict->objectForKey("itemHeight"))->intValue() / CC_CONTENT_SCALE_FACTOR();
		unsigned int startChar = ((CCString*)dict->objectForKey("firstChar"))->intValue();

		this.initWithString(theString, textureFilename, width, height, startChar);
*/
		return true;
	}

	/** initializes the CCLabelAtlas with a string, a texture, the width and height in points of each element and the starting char of the atlas */
	public boolean initWithString(final String string, CCTexture2D texture, int itemWidth, int itemHeight, int startCharMap) {
		ccMacros.CCAssert(string != null, "");
		if(super.initWithTexture(texture, itemWidth, itemHeight, string.length())) {
			m_uMapStartChar = startCharMap;
			this.setString(string);
			return true;
		}
		return false;
	}

	// super methods
	public void updateAtlasValues() {
		int n = m_sString.length();

		ccV3F_C4B_T2F_Quad quad = new ccV3F_C4B_T2F_Quad();

		final String s = m_sString;

		CCTexture2D texture = m_pTextureAtlas.getTexture();
		float textureWide = (float) texture.getPixelsWide();
		float textureHigh = (float) texture.getPixelsHigh();
		float itemWidthInPixels = m_uItemWidth * ccMacros.CC_CONTENT_SCALE_FACTOR();
		float itemHeightInPixels = m_uItemHeight * ccMacros.CC_CONTENT_SCALE_FACTOR();

		for(int i = 0; i < n; i++) {
			char a = (char) (s.charAt(i) - m_uMapStartChar);
			float row = (float) (a % m_uItemsPerRow);
			float col = (float) (a / m_uItemsPerRow);

			float left, right, top, bottom;

			if(ccConfig.CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL != 0) {
				// Issue #938. Don't use texStepX & texStepY
				left		= (2 * row * itemWidthInPixels + 1) / (2 * textureWide);
				right		= left + (itemWidthInPixels * 2 - 2) / (2 * textureWide);
				top			= (2 * col * itemHeightInPixels + 1) / (2 * textureHigh);
				bottom		= top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh);
			} else {
				left		= row * itemWidthInPixels / textureWide;
				right		= left + itemWidthInPixels / textureWide;
				top			= col * itemHeightInPixels / textureHigh;
				bottom		= top + itemHeightInPixels / textureHigh;
			} // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL

			quad.tl.texCoords.u = left;
			quad.tl.texCoords.v = top;
			quad.tr.texCoords.u = right;
			quad.tr.texCoords.v = top;
			quad.bl.texCoords.u = left;
			quad.bl.texCoords.v = bottom;
			quad.br.texCoords.u = right;
			quad.br.texCoords.v = bottom;

			quad.bl.vertices.x = (float) (i * m_uItemWidth);
			quad.bl.vertices.y = 0;
			quad.bl.vertices.z = 0.0f;
			quad.br.vertices.x = (float)(i * m_uItemWidth + m_uItemWidth);
			quad.br.vertices.y = 0;
			quad.br.vertices.z = 0.0f;
			quad.tl.vertices.x = (float)(i * m_uItemWidth);
			quad.tl.vertices.y = (float)(m_uItemHeight);
			quad.tl.vertices.z = 0.0f;
			quad.tr.vertices.x = (float)(i * m_uItemWidth + m_uItemWidth);
			quad.tr.vertices.y = (float)(m_uItemHeight);
			quad.tr.vertices.z = 0.0f;

			ccColor4B c = new ccColor4B( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
			quad.tl.colors.set(c);
			quad.tr.colors.set(c);
			quad.bl.colors.set(c);
			quad.br.colors.set(c);
			m_pTextureAtlas.updateQuad(quad, i);
		}
	}

	public void setString(final String label) {
		int len = label.length();
		if (len > m_pTextureAtlas.getTotalQuads()) {
			m_pTextureAtlas.resizeCapacity(len);
		}

		m_sString = label;
		this.updateAtlasValues();

		CCSize s = CCSize.Make(len * m_uItemWidth, m_uItemHeight);

		this.setContentSize(s);

		m_uQuadsToDraw = len;
	}

	public String getString() {
		return m_sString;
	}

	public void draw() {
		if(ccConfig.CC_LABELATLAS_DEBUG_DRAW != 0) {
			super.draw();

			final CCSize s = this.getContentSize();
			CCPoint [] vertices = {
					CCPointExtension.ccp(0, 0),
					CCPointExtension.ccp(s.width, 0),
					CCPointExtension.ccp(s.width, s.height),
					CCPointExtension.ccp(0, s.height),
			};
			CCDrawingPrimitives.ccDrawPoly(CCDirector.gl, vertices, 4, true);
		}
	}

	// string to render
	protected String m_sString;

	// the first char in the charmap
	protected int m_uMapStartChar;
}

// end of GUI group
/// @}
/// @}
