package com.yfd.monitor.gdw2019.event.status;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yfd.monitor.gdw2019.bean.*;
import com.yfd.monitor.gdw2019.transmit.cmd.ISIPCommanderForPlatform;
import com.yfd.monitor.storager.IVideoManagerStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.sip.InvalidArgumentException;
import javax.sip.SipException;
import java.text.ParseException;
import java.util.*;

/**
 * @description: 设备状态事件监听
 * @data: 2021-01-20
 */

@Component
public class StatusEventListener implements ApplicationListener<StatusEvent> {

    private final static Logger logger = LoggerFactory.getLogger(StatusEventListener.class);

    private static Map<String, SseEmitter> sseEmitters = new Hashtable<>();

    @Autowired
    private SubscribeHolder subscribeHolder;

    @Autowired
    private IVideoManagerStorage storager;
    @Autowired
    private ISIPCommanderForPlatform cmdforplatform;

    public void addSseEmitters(String browserId, SseEmitter sseEmitter) {
        sseEmitters.put(browserId, sseEmitter);
    }

    @Override
    public void onApplicationEvent(StatusEvent event) {
        // 获取所用订阅
        List<ParentPlatform> parentPlatforms = storager.queryEnableParentPlatformList(true);
        if (parentPlatforms.size()==0) return;
        ParentPlatform parentPlatform=parentPlatforms.get(0);
        SubscribeInfo subscribeinfo = subscribeHolder.getStatusSubscribe(parentPlatform.getServerGBId());

        Map<String,String> devicestatus=event.getDevicestatus();

        List<Map<String,String>> statusitems=new ArrayList<>();
        if(ObjUtil.isNotEmpty(subscribeinfo)){
            String items=subscribeinfo.getItems();
            JSONArray jsonArray= JSON.parseArray(items);
            for (Object o : jsonArray) {
                JSONObject jobj=(JSONObject) o;
                if(jobj.getString("Code").equals(devicestatus.get("Code").toString())) {//订阅了设备
                    statusitems.add(devicestatus);
                }
            }
        }

       if(statusitems.size()>0){
           try {
               SipTransactionInfo sipTransactionInfo = new SipTransactionInfo(subscribeinfo.getResponse());
               cmdforplatform.sendDeviceStatusNotice(parentPlatform,statusitems,sipTransactionInfo);
            } catch (ParseException e) {
               e.printStackTrace();
           } catch (InvalidArgumentException e) {
               e.printStackTrace();
           } catch (SipException e) {
               e.printStackTrace();
           }
       }
    }
}
