package com.wiki.standalone.moxkiriya.parser.blockparser;

import com.wiki.standalone.moxkiriya.WikiEngine;

public class WikiHnBlockParser extends WikiBlockParserBase {
	private static final String START_TAG = "<div><h%d ";

	private static final String END_TAG = "</h%d></div>\n";
	
	/** WIKI記法の正規表現文字列　行頭パターン */
	private static final String NOTATION_REGEX_LINEHEAD = "^==+";

	/** WIKI記法の正規表現文字列　行末パターン */
	private static final String NOTATION_REGEX_LINETAIL = "==+$";
	
	/** WIKI記法の正規表現文字列 */
	public static final String NOTATION_REGEX = NOTATION_REGEX_LINEHEAD
			+ "..*"
			+ NOTATION_REGEX_LINETAIL;

	/** 最大ヘッダレベル */
	public static final int HEADERLEVEL_MAX = 6;

	/** ヘッダレベル */
	private int headerLevel_;

	/** TOC(目次)構築クラス */
	private WikiTOCBuilder wikiTOCBuilder_;	

	/** 
	 *　 コンストラクタ
	 */
	public WikiHnBlockParser(WikiEngine wikiEngine, WikiTOCBuilder wikiTOCBuilder) {
		super(wikiEngine);
		wikiTOCBuilder_ = wikiTOCBuilder;
	}

	@Override
	public String startElementProcess(String line, StringBuffer buf) {
		int    startCount    = countToken(line, '=');
		int    lastCount     = 0;
		char[] lineCharArray = line.toCharArray();

		for(lastCount = 0; lastCount < line.length(); lastCount++) {
			if(lineCharArray[lineCharArray.length - lastCount - 1] != '=') {
				break;
			}
		}

		headerLevel_ = Math.min(Math.min(startCount, lastCount), HEADERLEVEL_MAX); 
		
		buf.append(String.format(START_TAG, headerLevel_));
		
		StringBuffer replaceString = new StringBuffer();
		for(int count = 0; count < headerLevel_; count++) {
			replaceString.append("=");
		}

		String headline = line.replaceFirst("^" + replaceString, "")
							.replaceFirst(replaceString + "$", "").trim();
		buf.append("id=\"" + headline + "\">");
		wikiTOCBuilder_.add(headline, headerLevel_);

		return headline;
	}

	@Override
	public String endElementProcess(String line, StringBuffer buf) {
		buf.append(String.format(END_TAG, headerLevel_));
		return "";
	}

	@Override
	public boolean isBlockEnd() {
		return true;
	}
}
