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

 //グローバルの名前空間用のオブジェクトを用意する
var TEXTOBJECT = {};

/**
 * get HTML Text Image URL
 */
TEXTOBJECT.getTextObjectImage = function(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;
	var newLine = false;
	var startPoint = 0;
	var flag = 0;
	var frontLine = 0;
	var startRight = 0;
	/* remove escape charactor '\' */
	dataHtml = htmlData.replace(/\\/, '');
	//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') {
		                	newLine = true;
		                    align = attrs[i].escaped;
		                    textAlign = align;
		                } else {
		                	newLine = false;
		                }
		            }
		            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';
		            newLine = false;
		            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);
		        }
		        if(newLine == true && flag > 0) {
		        	frontLine = currentLine;
		        	currentLine += nextLinePosition;
		        }  else if(flag == 0){
		        	currentLine = 20;
		        }
		        flag++;
		        /*
		        * Uタグ
		        */
		        if (t == 'u') {
		            hasUnderLine = true;
		        } else {
		        	hasUnderLine = false;
		        }
		    },

		    end: function (tag) {

		        var t = tag.toLowerCase();
		        console.log("the"+t);
		        /*
		        * 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(currentLine > frontLine) {
	                		if(newLine == false) {
		                		startPoint = startPosition;
		                	} else {
		                		startPoint = 0;
		                		startPosition = 0;
		                	}
			            } else {
				            startPoint = startPosition;
			            }
		                if (textAlign == 'left') {
		                    x1 = startPoint;
		                    x2 = startPoint + metrices.width;
		                } else if (textAlign == 'center') {
		                    x1 = startPoint - (metrices.width / 2);
		                    x2 = startPoint + (metrices.width / 2);
		                } else if (textAlign = 'right') {
		                    x1 = width;
		                    x2 = width - metrices.width;
		                }
		                context.beginPath();
		                context.moveTo(x1, currentLine + margin);
                		context.lineTo(x2, currentLine + margin);
		                context.strokeStyle = context.fillStyle;
		                context.stroke();
		            }
		            startPosition +=metrices.width;
		            //currentLine += (nextLinePosition + margin);
		        }
		    }
		}
	);
	//context.fillText("helloworld",0, currentLine + margin);
	// 描画したイメージを返却する
	var imageUrl = canvas.toDataURL();
	return imageUrl;
};
