package cn.reghao.bnt.agent.ws.event;

import cn.reghao.bnt.agent.ws.event.handler.EvtAppDeployHandler;
import cn.reghao.bnt.agent.ws.event.handler.EvtAppStatHandler;
import cn.reghao.bnt.common.agent.app.iface.AppDeploy;
import cn.reghao.bnt.common.agent.app.iface.AppStat;
import cn.reghao.bnt.common.msg.MessageSender;
import cn.reghao.bnt.common.msg.event.EvtAppDeploy;
import cn.reghao.bnt.common.msg.event.EvtAppStat;
import cn.reghao.jutil.jdk.event.message.Event;
import cn.reghao.jutil.jdk.event.message.EventMessage;
import cn.reghao.jutil.jdk.event.router.EventDispatcher;
import cn.reghao.jutil.jdk.exception.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.management.ManagementFactory;

/**
 * @author reghao
 * @date 2023-02-23 09:18:11
 */
@Slf4j
public class EventCenter {
    private final long startTime;
    private final EventDispatcher dispatcher;

    public EventCenter(MessageSender messageSender, AppDeploy appDeploy, AppStat appStat) {
        this.startTime = ManagementFactory.getRuntimeMXBean().getStartTime();
        this.dispatcher = new EventDispatcher();
        initDispatcher(messageSender, appDeploy, appStat);
    }

    private void initDispatcher(MessageSender messageSender, AppDeploy appDeploy, AppStat appStat) {
        dispatcher.register(EvtAppDeploy.class, new EvtAppDeployHandler(messageSender, appDeploy));
        dispatcher.register(EvtAppStat.class, new EvtAppStatHandler(messageSender, appStat));
    }

    public void dispatch(EventMessage eventMessage) {
        try {
            long sendTime = eventMessage.getSendTime();
            if (sendTime < startTime) {
                log.info("忽略 agent 启动前 mgr 发送的事件...");
                return;
            }

            Event event = eventMessage.getEvent();
            dispatcher.dispatch(event);
        } catch (Exception e) {
            String errMsg = e.getMessage();
            if (e instanceof NullPointerException) {
                errMsg = ExceptionUtil.stackTrace(e);
            }

            log.error("处理消息发生异常: {}", errMsg);
        }
    }
}
