package com.sv.socket;

import com.common.DeviceDTO;
import com.enums.DeviceStatusEnum;
import com.sv.entity.Device;
import com.sv.service.oms.DeviceService;
import com.ydd.framework.core.common.dto.ResponseDTO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class DeviceController {

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


    @Resource
    private ApplicationContext applicationContext;


    @Resource
    private DeviceService deviceService;

    @RequestMapping("/device/reconnect/{id}")
    public ResponseDTO reconnect(@PathVariable("id") Integer deviceId) {
        Device device = deviceService.findById(deviceId);
        synchronized (device.getStream().intern()) {
            if (device != null && DeviceStatusEnum.OFFLINE.value.equals(device.getStatus())) {
                deviceService.reconnect(deviceId);
                try {
                    DeviceDTO deviceDTO = new DeviceDTO();
                    BeanUtils.copyProperties(device, deviceDTO);
                    URI uri = new URI("ws://" + faceUrl + "/video?url=" + URLEncoder.encode(device.getStream(), "utf-8"));
                    DeviceSocket client = new DeviceSocket(applicationContext, deviceDTO, uri);
                    client.connectBlocking();
                } catch (Exception e) {
                    e.printStackTrace();
                    deviceService.offline(deviceId);
                }
            }
            return ResponseDTO.ok();
        }

    }

}
