package cc.smtweb.framework.core.container.factory;

import cc.smtweb.framework.core.container.base.IListenerIntf;
import cc.smtweb.framework.core.container.base.SwParameter;
import cc.smtweb.framework.core.container.base.SwReturn;
import cc.smtweb.framework.core.systask.SysThreadPool;
import cc.smtweb.framework.core.systask.SysThreadWorker;

import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Akmm at 12-3-22 下午4:45
 * 事件监听工厂
 */
public class ListenerFactory {
    private static Map<String, List<IListenerIntf>> map;

    static {
        map = new ConcurrentHashMap<>(64);
    }

    /**
     * 注册监听
     *
     * @param event    事件名
     * @param listener 监听类
     */
    public static void reg(String event, IListenerIntf listener) {
        List<IListenerIntf> list = map.get(event);
        if (list == null) {
            synchronized (ListenerFactory.class) {
                list = map.get(event);
                if (list == null) {
                    list = new Vector<>();
                    map.put(event, list);
                }
            }
        }
        list.add(listener);
    }

    /**
     * 取消注册监听
     *
     * @param event    事件名
     * @param listener 监听类
     */
    public static void remove(String event, IListenerIntf listener) {
        List<IListenerIntf> list = map.get(event);
        if (list != null) list.remove(listener);
    }

    /**
     * 取消指定事件所有监听
     *
     * @param event 事件名
     */
    public static void clear(String event) {
        map.remove(event);
    }

    /**
     * 执行监听
     *
     * @param event 事件名
     * @param param 事件参数
     * @param result 监听程序的执行结果
     * @throws Exception
     */
    public static void fireListener(String event, SwParameter param, SwReturn result)throws Exception{
        List<IListenerIntf> list = map.get(event);
        if (list == null) return;
        for (IListenerIntf listener : list) {
            listener.doWork(param, result);
            if (!result.isSuccess()) return;
        }
    }

    /**
     * 执行监听
     *
     * @param event 事件名
     * @param param 事件参数
     * @throws Exception
     */
    public static void fireListener(String event, SwParameter param) throws Exception {
        SwReturn result = new SwReturn();
        fireListener(event, param, result);
        if (!result.isSuccess()) throw new Exception(result.getMessageStr());
    }
    /**
     * 执行监听\异步执行
     *
     * @param event 事件名
     * @param param 事件参数
     * @throws Exception
     */
    public static void fireListenerAsyc(String event, SwParameter param){
        SysThreadPool.getInstance().addTask(new SysThreadWorker() {
            @Override
            public void localWork() throws Exception {
                try {
                    fireListener(event, param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
