package org.aohe.web;

import lombok.extern.slf4j.Slf4j;
import org.aohe.result.R;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import static org.aohe.control.Operational.selectOperational;

@Slf4j
public class SocketServer extends WebSocketServer {

    public SocketServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

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

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        //conn.send("Welcome to the server!"); // This method sends a message to the new client
        //broadcast("new connection: " + handshake.getResourceDescriptor()); // This method sends a message to all clients connected
        //System.out.println(conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
        log.info("ws用户已连接");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        log.info("ws用户关闭连接");
        //这里执行关闭扫描仪连接
    }

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

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        log.info(ex.getMessage());
        if (conn != null) {
            conn.send(R.fail("error").toJsonStr());
            //绑定不到就退出
            //System.exit(0);
            // some errors like port binding failed may not be assignable to a specific
            // websocket
        }

    }

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

    }

    public void broadcastNew(String message) {
    }

    public void broadcastNew(byte[] bytes) {
    }

}
