package org.aohe.web;

import lombok.extern.slf4j.Slf4j;
import org.aohe.result.R;
import org.aohe.webcam.WebCamUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CamSocketServer extends SocketServer {

    private static final Map<String, WebSocket> map = new HashMap<>();

    public CamSocketServer(int port) throws UnknownHostException {
        super(port);
    }

    public CamSocketServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        log.info("Cam-ws用户连接 {}", conn.getProtocol().toString());
        map.put("zero", conn);
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        log.info("Cam-ws用户关闭连接");
        if(map.get("zero") == conn){
            WebCamUtils.closeWebcamTransfer();
        }
        //这里执行关闭连接
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        log.info("用户发送了数据：\n {}", message);
        conn.send(R.ok().toJsonStr());
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        log.info(ex.getMessage());
        if (conn != null) {
            conn.send(R.fail("error").toJsonStr());
            //绑定不到就退出
        }

    }

    @Override
    public void onStart() {
        log.info("Server started!");
        setConnectionLostTimeout(0);
        setConnectionLostTimeout(100);

    }

    @Override
    public void broadcastNew(String message) {
        if (message == null){
            return;
        }
        WebSocket zero = map.get("zero");
        if(zero!=null && zero.isOpen()){
            map.get("zero").send(message);
        }
    }

    @Override
    public void broadcastNew(byte[] bytes) {
        if (bytes == null){
            return;
        }
        WebSocket zero = map.get("zero");
        if(zero != null && zero.isOpen()){
            zero.send(bytes);
        }
    }

}

