package com.mingsoft.regex.prase;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mingsoft.constant.JspPage;
import com.mingsoft.io.IoReader;
import com.mingsoft.regex.Regex;
import com.mingsoft.regex.RegexEnum;
import com.mingsoft.util.RegexUtil;
/**
 * 引入文件标签 ,主要用于引入公用的HTML等文件 .filename 是相对ms:global.skin下面的文件名称(单标签)
 * 网站全局标签
 * {ms:include filename="url"/}
 * @author 成卫雄
 * QQ:330216230
 * 技术支持：景德镇铭飞科技
 * 官网：www.ming-soft.com
 */
public class IncludePrase extends Regex {
	/**
	 * 文件的路径
	 */
	String path;
	
	public IncludePrase(String htmlContent,String path){
		super.htmlCotent = htmlContent;
		this.path = path;
	}
	
	@Override
	public String parse() {
		String html = super.htmlCotent; 
		int strNum = includeNum(super.htmlCotent);
		while(strNum != 0){
				//取出模版内容
				String htmlInclude = includeContentPrase(super.htmlCotent,path);
				super.newCotent = htmlInclude;
				//将取出的内容替换标签
				html = super.replaceFirst(RegexEnum.INCLUDE);
			strNum = includeNum(html);
		}
		
		return html;
	}
	
	/**
	 * 获取模中的要替换的引入文件的名字并读取出该文件
	 * @param html html模版
	 * @param path 文件的项目路径
	 * @return 返回读取出来的文件HTML
	 */
	private static String includeContentPrase(String html,String path){
		String includeContent = "";
		Pattern patternL = Pattern.compile(RegexEnum.INCLUDE.getRegex());
		Matcher matcherL = patternL.matcher(html);
		if(matcherL.find()){
			String includeName = matcherL.group(1);
			//判断include文件是否存在
			File file = new File(path+JspPage.PATH_SYMBOL+includeName);
			if(!file.exists()){
				includeContent = includeName+"不存在，请仔细检查该模版的文件！";
			}else{
				includeContent = IoReader.readFile(path+JspPage.PATH_SYMBOL+includeName);
			}
		}
		return includeContent;
	}
	
	/**
	 *获取模版文件中引入标签的个数 
	 * @param html 文件模版
	 * @return 返回该字符串的个数
	 */
	private int includeNum(String html){
		int includeNum = RegexUtil.regexNum(html, RegexEnum.INCLUDE);
		return includeNum;
	}
}
