package com.example.fuzzControll.service.impl;

import com.example.fuzzControll.conf.IntegrationPathProperties;
import com.example.fuzzControll.service.websocketClientService;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;

@Slf4j
@Service("websocketClientService")
public class websocketClientServiceImpl implements websocketClientService {
    public static WebSocketClient webSocketClient = null;
    @Autowired
    IntegrationPathProperties properties;
    @Override
    public void connect() {
        try {
            webSocketClient = new WebSocketClient(new URI(properties.getWebSocketUri()+"fuzzIntegration")) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("connect...");
                }

                @Override
                public void onMessage(String s) {
                    log.info("get message:{}", s);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    log.info("disconnect code:{} reason:{} {}", i, s, b);
                }

                @Override
                public void onError(Exception e) {
                    log.info("connect error!");
                }
            };
            webSocketClient.connect();
        }catch (URISyntaxException e){
            e.printStackTrace();
        }
    }

    @Override
    public void disconnect() {
        try {
            webSocketClient.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}