package com.aliyun.sca.client;

import com.aliyun.sca.listener.WebSocketListener;
import lombok.Getter;
import lombok.Setter;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.concurrent.CountDownLatch;

/**
 * @author huyanan
 * @date 2025/1/6
 */
public class ScaWebSocketClient extends WebSocketClient {
    private static final String HEARTBEAT_MESSAGE = "HeartBeat";
    private static final Logger logger = LoggerFactory.getLogger(ScaWebSocketClient.class);
    private final WebSocketListener listener;
    @Getter
    private final CountDownLatch openFlag = new CountDownLatch(1);

    @Getter
    @Setter
    private Long lastMessageTime;

    @Getter
    @Setter
    private boolean comleteQualityUser = false;

    @Getter
    @Setter
    private boolean comleteQualityAgent = false;

    @Getter
    @Setter
    private boolean completeUpdate = false;

    public void initLastMessageTime() {
        this.lastMessageTime = null;
    }


    public ScaWebSocketClient(URI uri, WebSocketListener listener) {
        super(uri);
        this.lastMessageTime = System.currentTimeMillis();
        this.listener = listener;
    }

    @Override
    public void send(String message) {
        this.lastMessageTime = System.currentTimeMillis();
        super.send(message);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        openFlag.countDown();
    }

    @Override
    public void onMessage(String message) {
        if (HEARTBEAT_MESSAGE.equals(message)) {
            System.out.println(HEARTBEAT_MESSAGE);
            return;
        }

        listener.onMessage(message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        logger.info("websocket close - reason: "+ reason + "is remote" + remote);

    }

    @Override
    public void onError(Exception ex) {
        logger.error("websocket error: "+ ex.getMessage());
    }
}
