package com.yaohun.mcbot;

import com.yaohun.mcbot.client.QQWebSocketClient;
import com.yaohun.mcbot.commands.BindAdminCmd;
import com.yaohun.mcbot.commands.BindTencentCmd;
import com.yaohun.mcbot.config.Config;
import com.yaohun.mcbot.data.sql.SQLIO;
import com.yaohun.mcbot.listsener.FriendListener;
import com.yaohun.mcbot.listsener.GroupListener;
import com.yaohun.mcbot.manage.CacheManager;
import com.yaohun.mcbot.manage.WssReconnectManager;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class McBot extends Plugin {

    private static McBot instance;

    private static WssReconnectManager wssManager;

    @Override
    public void onEnable() {
        instance = this;
        getLogger().info("[McBot] Start Plugins ...");
        Config.reloadConfig(this);
        SQLIO.init(); // 激活MySQL - 数据库的连接

        String serverUri = "ws://127.0.0.1:6050";
        WssReconnectManager.initialize(this, serverUri);

        QQWebSocketClient client = new QQWebSocketClient(serverUri);
        WssReconnectManager.setClient(client);
        client.connect();

        getProxy().getPluginManager().registerCommand(this, new BindTencentCmd());
        getProxy().getPluginManager().registerCommand(this, new BindAdminCmd());

        getProxy().getPluginManager().registerListener(this, new GroupListener());
        getProxy().getPluginManager().registerListener(this, new FriendListener());

        ProxyServer.getInstance().getScheduler().schedule(this, CacheManager::checkingCleanUpData, 1L, 5L, TimeUnit.MINUTES);
    }

    @Override
    public void onDisable() {
        SQLIO.closeConnection(); // 关闭MySQL - 数据库的连接
        getLogger().info("[WebSocket] 插件卸载，准备关闭 WebSocket 通道...");
        QQWebSocketClient client = WssReconnectManager.getClient();
        if (client != null && client.isOpen()) {
            try {
                client.close(); // 发送关闭帧 + 关闭资源
                getLogger().info("[WebSocket] WebSocket 通道已成功关闭。");
            } catch (Exception e) {
                getLogger().warning("[WebSocket] 关闭通道时出现异常: " + e.getMessage());
            }
        }
    }


    public static McBot inst() {
        return instance;
    }
}
