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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

@Component
public class SocketReconnectListener implements ApplicationListener<SocketReconnectEvent> {

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

    @Value("${face.url}")
    private String faceUrl;

    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private DeviceService deviceService;

    @Async
    @Override
    public void onApplicationEvent(SocketReconnectEvent event) {
        Long current = System.currentTimeMillis();
        if(current - event.getDevice().getLastCloseTime() > (1000 * 60)){
            //重新连接超过一分钟 timeout
            logger.info("设备【{}】重新连接超时",event.getDevice().getStream());
            deviceService.offline(event.getDevice().getId());
            event.getDevice().setLastCloseTime(null);
            return;
        }
        DeviceDTO device = event.getDevice();
        logger.info("设备【{}】开始重新连接",device.getStream());
        deviceService.setReconnect(device.getId());
        if(device != null){
            URI uri = null;
            try {
                uri = new URI( "ws://"+faceUrl+":9000/video?url="+ URLEncoder.encode(device.getStream(),"utf-8"));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            DeviceSocket client = new DeviceSocket(applicationContext,device,uri);
            try {
                client.connectBlocking();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
