package cn.iocoder.yudao.module.pms.controller.admin.yanfan.sip.handler.req.message.notify.cmdType;

import cn.iocoder.yudao.module.pms.controller.admin.yanfan.sip.handler.req.message.IMessageHandler;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.sip.handler.req.message.notify.NotifyMessageHandler;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.sip.device.YfSipDeviceDO;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.IMqttService;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.MessageInvoker;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.msg.Alarm;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.msg.SipMessage;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.RequestEvent;

@Slf4j
@Component
public class AlarmHandler implements InitializingBean, IMessageHandler {

    @Autowired
    private NotifyMessageHandler notifyMessageHandler;

    @Autowired
    private MessageInvoker messageInvoker;

    @Autowired
    private IMqttService mqttService;

    @Override
    public void handlerCmdType(RequestEvent evt, YfSipDeviceDO device, Element element) {
        log.info("设备报警：{}", device.getDeviceId());
        SipMessage message = messageInvoker.messageToObj(evt);
        if (message instanceof Alarm) {
            log.info("报警内容：{}", message);
            mqttService.publishEvent((Alarm) message);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String cmdType = "Alarm";
        notifyMessageHandler.addHandler(cmdType, this);
    }
}
