package com.yaohun.mcbot.manage;

import com.yaohun.mcbot.McBot;
import com.yaohun.mcbot.client.QQWebSocketClient;
import net.md_5.bungee.api.ProxyServer;

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

public class WssReconnectManager {

    private static final int MAX_RETRY = 5;
    private static final long RETRY_DELAY_SECONDS = 15;

    private static boolean reconnecting = false;

    private static int retryCount = 0;

    private static QQWebSocketClient currentClient;
    private static String serverUri;
    private static McBot plugin;

    public static void initialize(McBot pluginInstance, String uri) {
        plugin = pluginInstance;
        serverUri = uri;
    }

    public static void setClient(QQWebSocketClient client) {
        currentClient = client;
    }

    public static QQWebSocketClient getClient() {
        return currentClient;
    }

    public static void tryReconnect() {
        if (reconnecting) return;

        if (currentClient != null && currentClient.isOpen()) return;

        if (retryCount >= MAX_RETRY) {
            plugin.getLogger().severe("[Bot-WebSocket] 已达到最大重连次数，停止尝试");
            return;
        }

        reconnecting = true;
        retryCount++;

        ProxyServer.getInstance().getScheduler().schedule(plugin, () -> {
            try {
                // 关闭旧连接
                if (currentClient != null && currentClient.isOpen()) {
                    plugin.getLogger().info("[Bot-WebSocket] 关闭旧连接...");
                    currentClient.close();
                }

                plugin.getLogger().info("[Bot-WebSocket] 重新连接尝试 第<" + retryCount + ">次 ...");
                QQWebSocketClient newClient = new QQWebSocketClient(serverUri);
                setClient(newClient);
                newClient.connect();
            } catch (Exception e) {
                plugin.getLogger().severe("[Bot-WebSocket] 重连失败: " + e.getMessage());
                e.printStackTrace();
            } finally {
                reconnecting = false;
            }
        }, RETRY_DELAY_SECONDS, TimeUnit.SECONDS);
    }

    public static void resetRetry() {
        retryCount = 0;
    }
}
