package com.sifang.modules.sys.extention.permission;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.util.List;
import java.util.Map;

public abstract class AbstractPermissionFilter {

    public static Map<String, String> TAGMAP = Maps.newHashMap();

    static{
        initTagMap();
    }

    public static void initTagMap(){
        List<Record> rds = Db.find("select * from sys_menu_pro a where a.status = '0' and a.target in ('1', '2')");
        for(Record rd : rds){
            TAGMAP.put(rd.getStr("permission"), rd.getStr("id"));
        }
    }

    List<PermissionHandler> handlers;

    PermissionVo vo;

    protected abstract void bindHandlers();

    public AbstractPermissionFilter registerHandler(PermissionHandler handler){
        return register(handler);
    }

    public AbstractPermissionFilter registerStart(PermissionHandler handler){
        return register(handler);
    }

    public AbstractPermissionFilter registerEnd(PermissionHandler handler){
        return register(handler);
    }

    private AbstractPermissionFilter register(PermissionHandler handler){
        if(this.handlers == null){
            handlers = Lists.newArrayList();
        }
        handlers.add(handler);
        return this;
    }

    public void process(){
        bindHandlers();
        for(PermissionHandler handler : handlers){
            handler.handler(vo);
        }
    }

    public String parseAuthTagToMenuId(String authTag){
        return TAGMAP.get(authTag);
    }

    public List<PermissionHandler> getHandlers() {
        return handlers;
    }

    public void setHandlers(List<PermissionHandler> handlers) {
        this.handlers = handlers;
    }

    public PermissionVo getVo() {
        return vo;
    }

    public void setVo(PermissionVo vo) {
        this.vo = vo;
    }
}
