package com.sv.socket.event;

import com.common.DeviceDTO;
import com.sv.entity.Device;
import com.sv.service.oms.DeviceService;
import com.sv.socket.DeviceSocket;
import com.sv.socket.SocketConnections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class SocketConnectListener implements ApplicationListener<SocketConnectEvent> {

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

    @Resource
    private DeviceService deviceService;

    @Override
    @Async
    public void onApplicationEvent(SocketConnectEvent event) {
        boolean flag = false;
        try {
            //等待三秒 如果断开连接了 则表示没有连接成功
            flag = event.getCountDownLatch().await(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!flag) {
            DeviceDTO device = event.getDevice();
            SocketConnections.sockets.put(device.getStream(),event.getDeviceSocket());
            device.setLastCloseTime(null);
            logger.info("设备【{}】连接成功", device.getStream());
            deviceService.online(device.getId());
        }
    }
}
