package org.beetl.core.engine;

import org.beetl.core.Context;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Resource;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.statement.*;

import java.io.IOException;

/**
 * 定制模板引擎，当出现变量不存在的异常，原样输出而不是报错
 */
public class MyPlaceHolderEngine extends  DefaultTemplateEngine{

	protected GrammarCreator getGrammarCreator(GroupTemplate groupTemplate) {
		GrammarCreator result = new MyPlaceHolderGrammarCreator();
		return result;
	}

	static class MyPlaceHolderGrammarCreator extends  GrammarCreator{

		@Override
		public PlaceholderST createTextOutputSt(Expression exp, FormatExpression format) {

			if(exp instanceof VarRef){
				// #{a.c} 最简单的变量输出
				return new TextShow(exp, format, null);
			}else{
				return  new PlaceholderST(exp,format,null);
			}

		}
	}

	public static class TextShow extends PlaceholderST{

		public TextShow(Expression exp, FormatExpression format, GrammarToken token) {
			super(exp, format, token);
		}

		@Override
		public void execute(Context ctx) {
			try{
				super.execute(ctx);
			}catch (BeetlException ex){
				if(ex.detailCode.equals(BeetlException.VAR_NOT_DEFINED)){
					showText(ctx);
					return ;
				}
				throw ex;
			}
		}
		protected void showText(Context ctx){
			String start1 = ctx.template.gt.getConf().getPlaceholderStart();
			String end1 = ctx.template.gt.getConf().getPlaceholderEnd();
			try{
				ctx.byteWriter.writeString(start1);
				ctx.byteWriter.writeString(getText(expression));
				ctx.byteWriter.writeString(end1);
			}catch (IOException ioe){
				//do nothing
			}

		}

		protected  String getText(Expression expression){
			if(expression instanceof  VarRef){
				VarRef ref = (VarRef)expression;
				return ref.token.text;
			}

			throw new UnsupportedOperationException("不支持的表达式");
		}
	}

}
