package com.sunxung.factoring.component.tag;

import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import com.sunxung.factoring.component.cache.RedisCache;
import com.sunxung.factoring.component.util.FormTokenUtil;
import com.sunxung.factoring.component.util.SpringUtil;

/**
 * @ClassName:TokenTag
 * @Description:页面生成token值的tag标签
 * @Author:duxiaojiao
 * @E-mail:1261237207@qq.com
 * @Date:2017年6月21日 下午4:12:51
 */
public class TokenTag extends AbstractAttributeTagProcessor {

    private static String ATTR_NAME = "token";
    private static int PRECEDENCE = 10000;
    private static RedisCache redisCache;

    public TokenTag(final String dialectPrefix){
        super(TemplateMode.HTML, dialectPrefix, null, false, ATTR_NAME, true, PRECEDENCE, true);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName,
            String attributeValue, IElementTagStructureHandler structureHandler) {
        StringBuffer sb = new StringBuffer();
        String tokenValue = FormTokenUtil.generateGUID();
        sb.append("<input type='hidden' name='" + FormTokenUtil.TOKEN_NAME + "' value='").append(tokenValue)
                .append("'/>");
        getRedisCache().set(tokenValue, tokenValue);
        structureHandler.setBody(sb.toString(), false);
    }

    private RedisCache getRedisCache() {
        if (redisCache == null) {
            redisCache = SpringUtil.getBeanByType(RedisCache.class);
        }
        return redisCache;
    }
}
