package com.sv.socket;

import com.common.DeviceDTO;
import com.sv.entity.Device;
import com.sv.service.api.AboutUsService;
import com.sv.service.oms.DeviceService;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URLEncoder;
import java.util.List;

@Component
public class SocketStarter implements CommandLineRunner {

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

    @Resource
    private DeviceService deviceService;

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


    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        logger.info("开始连接设备socket");
        List<DeviceDTO> devices = deviceService.findAll();
        if (devices != null && devices.size() > 0) {
            for(DeviceDTO device : devices){
                if(SocketConnections.sockets.get(device.getStream()) != null)
                    continue;
                URI uri = new URI( "ws://"+faceUrl+":9000/video?url="+ URLEncoder.encode(device.getStream(),"utf-8"));
                DeviceSocket client = new DeviceSocket(applicationContext,device,uri);
                client.connectBlocking();
            }
        }
        logger.info("连接设备完毕！");
    }
}
