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.util.SpringUtil;
import com.sunxung.factoring.service.sys.AuthorityService;

/**
 * 权限tag标签
 */
public class PermissionTag extends AbstractAttributeTagProcessor {

    private static String ATTR_NAME = "hasPermission";
    private static int PRECEDENCE = 10000;
    private static AuthorityService authorityService;

    public PermissionTag(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) {
        if (!getAuthorityService().hasPermission(attributeValue)) {
            structureHandler.removeElement();
        }
    }

    private AuthorityService getAuthorityService() {
        if (authorityService == null) {
            authorityService = SpringUtil.getBeanByType(AuthorityService.class);
        }
        return authorityService;
    }
}
