package com.jpsoft.shinestar.listener;

import com.jpsoft.ehome.callback.DeviceRegisterCallBack;
import com.jpsoft.ehome.callback.MsgNoticeCallBack;
import com.jpsoft.ehome.config.EHomeParamConfig;
import com.jpsoft.ehome.device.EHomeSDK;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@Slf4j
@WebListener
@Component
@Profile({"test","production"})
public class EhomeWebListener implements ServletContextListener {
    @Autowired
    private EHomeSDK eHomeSDK;

    @Autowired
    private EHomeParamConfig eHomeConfig;

    @Autowired
    private DeviceRegisterCallBack deviceRegisterCallBack;

    @Autowired
    private MsgNoticeCallBack msgNoticeCallBack;

    private int alarmListenHandle;

    private int essListenerHandle;

    private int cmsListenerHandle;

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        System.out.println("ehome初始化");

        if (eHomeSDK !=null){
            try {
                //设备注册回调时要读取报警服务和存储服务的IP和端口，如果配置文件中错误则无法接受预警信息
                log.warn(eHomeConfig.toString());

                alarmListenHandle = eHomeSDK.startAlarmListen(eHomeConfig,msgNoticeCallBack);
                log.warn("startAlarmListen :" + alarmListenHandle);

                essListenerHandle = eHomeSDK.startESSListen(eHomeConfig);
                log.warn("startESSListen :" + essListenerHandle);

                cmsListenerHandle = eHomeSDK.startCMSListen(eHomeConfig,deviceRegisterCallBack);
                log.warn("startCMSListen :" + cmsListenerHandle);
            }
            catch (Exception ex){
                log.error(ex.getMessage(),ex);
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
        log.warn("ehome销毁");

        if (eHomeSDK !=null){
            if(eHomeSDK.stopAlarmListen(this.alarmListenHandle)){
                log.warn("已停止报警监听!");
            }

            if(eHomeSDK.stopESSListen(essListenerHandle)){
                log.warn("已停止存储监听!");
            }

            if(eHomeSDK.stopCMSListen(cmsListenerHandle)){
                log.warn("已停止注册监听!");
            }
        }
    }
}
