/**
 *  ABook Viewer for WEB
 *	Drawing HTML Text Library
 *	**this library depend on htmlparser.js**
 *  Copyright (C) Agentec Co, Ltd. All rights reserved.
 */

/**
 * get HTML Text Image URL 
 */
function getTextObjectImage(width, height, htmlData) {
	
	var canvas = document.createElement('canvas');
	canvas.width = width;
	canvas.height = height;
	
	var context = canvas.getContext('2d');
	var dataHtml = '';
	var currentLine = 0;
	var lineHeight = 0;
	var nextLinePosition = 0;
	var lineWidth = width;			// 1行の幅
	var startPosition = 0;			// テキスト描画の開始位置
	var hasUnderLine = false;		// アンダーラインの有無
	var textAlign = 'left';			// テキスト揃え
	var margin = 2;
	
	/* remove escape charactor '\' */
	dataHtml = htmlData.replace(/\\/, '');
	//dataHtml = dataHtml.toLowerCase();
	
	//console.log('dataHtml:' + dataHtml);
	
	// parse
	HTMLParser(dataHtml,
		{
		    start: function (tag, attrs, unary) {

		        var t = tag.toLowerCase();

		        /*
		        * DIVタグ
		        */
		        if (t == 'div') {
		            var align;
		            for (var i = 0; i < attrs.length; i++) {
		                var attrName = attrs[i].name.toLowerCase();
		                if (attrName == 'align') {
		                    align = attrs[i].escaped;
		                    textAlign = align;
		                }
		            }
		            if (align == 'left') {
		                startPosition = 0;
		                context.textAlign = 'left';
		            } else if (align == 'center') {
		                startPosition = lineWidth / 2;
		                context.textAlign = 'center';
		            } else if (align == 'right') {
		                startPosition = lineWidth;
		                context.textAlign = 'right';
		            }
		        }

		        /*
		        * FONTタグ
		        */
		        if (t == 'font') {
		            var fontFace = 'ＭＳ Ｐゴシック';
		            var fontSize = '11px';
		            var fontColor = '#000000';
		            for (var i = 0; i < attrs.length; i++) {

		                var attrName = attrs[i].name.toLowerCase();

		                if (attrName == 'face') {
		                    fontFace = attrs[i].escaped;
		                }
		                if (attrName == 'style') {
		                    var styleBase = attrs[i].escaped;
		                    var styles = styleBase.split(';');
		                    for (var j = 0; j < styles.length; j++) {
		                        var style = styles[j].split(':');
		                        if (style[0].toLowerCase() == 'font-size') {
		                            fontSize = style[1];
		                        }
		                        if (style[0].toLowerCase() == 'line-height') {
		                            lineHeight = parseInt(style[1].replace('px', ''));
		                        }
		                    }
		                }
		                if (attrName == 'color') {
		                    fontColor = attrs[i].escaped;
		                }
		            }
		            // context に設定
		            context.font = fontSize + " " + "'" + fontFace + "'";
		            context.fillStyle = fontColor;

		            // 行間  
		            nextLinePosition = parseInt(fontSize.replace('px', '')) * (lineHeight / 100);
		            
		        }

		        /*
		        * BR タグ
		        */
		        if (t == 'br') {
		            currentLine += (nextLinePosition + margin);
		        }

		        /*
		        * Uタグ
		        */
		        if (t == 'u') {
		            hasUnderLine = true;
		        }
		    },

		    end: function (tag) {

		        var t = tag.toLowerCase();

		        /*
		        * Uタグ
		        */
		        if (t == 'u') {
		            hasUnderLine = false;
		        }
		    },

		    chars: function (text) {

		        // エンティティ文字を置換
		        // &nbsp; &gt; &lt; &amp; &yen; &copy; &reg; のみ対応
		        text = text.replace(/&nbsp;/g, ' ');
		        text = text.replace(/&gt;/g, '>');
		        text = text.replace(/&lt;/g, '<');
		        text = text.replace(/&amp;/g, '&');
		        text = text.replace(/&copy;/g, '(C)');
		        text = text.replace(/&reg;/g, '(R)');
		        text = text.replace(/&yen;/g, '\\');

		        // 初期描画位置を考慮
		        if (currentLine == 0) {
		            //2014/02 フォントを大きくすると文字の上側が隠れる問題の対応
		            //currentLine += nextLinePosition / 2;
		            currentLine += nextLinePosition;
		        }

		        //長い文字列を考慮する
		        var w = 0;
		        var index = 0;
		        var fillText = '';
		        for (var i = 0; i < text.length; i++) {
		            var metrices = context.measureText(fillText + text.charAt(i), startPosition, currentLine);

		            // 幅に収まるならバッファに蓄える
		            if (metrices.width < lineWidth) {
		                fillText += text.charAt(i);
		            }
		            // はみ出す場合
		            else {
		                context.fillText(fillText, startPosition, currentLine + margin);
		                // アンダーライン
		                if (hasUnderLine) {
		                    context.beginPath();
		                    context.moveTo(0, currentLine + margin);
		                    context.lineTo(lineWidth, currentLine + margin);
		                    context.strokeStyle = context.fillStyle;
		                    context.stroke();
		                }

		                currentLine += (nextLinePosition + margin);
		                fillText = text.charAt(i);
		            }
		        }
		        if (fillText.length > 0) {
		            context.fillText(fillText, startPosition, currentLine + margin);
		            // アンダーライン
		            if (hasUnderLine) {
		                var x1, x2;
		                if (textAlign == 'left') {
		                    x1 = 0;
		                    x2 = metrices.width;
		                } else if (textAlign == 'center') {
		                    x1 = startPosition - (metrices.width / 2);
		                    x2 = startPosition + (metrices.width / 2);
		                } else if (textAlign = -'right') {
		                    x1 = startPosition;
		                    x2 = startPosition - metrices.width;
		                }
		                context.beginPath();
		                context.moveTo(x1, currentLine + margin);
		                context.lineTo(x2, currentLine + margin);
		                context.strokeStyle = context.fillStyle;
		                context.stroke();
		            }
		            currentLine += (nextLinePosition + margin);
		        }
		    }
		}
	);
	
	// 描画したイメージを返却する
	var imageUrl = canvas.toDataURL();
	return imageUrl;
};
