package com.yaohun.mcbot.client;

import com.yaohun.mcbot.McBot;
import com.yaohun.mcbot.MessageForwarder;
import com.yaohun.mcbot.manage.WssReconnectManager;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class QQWebSocketClient extends WebSocketClient {

    public QQWebSocketClient( String serverUri) {
        super(URI.create(serverUri));
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        McBot.inst().getLogger().info("[WebSocket-Link] connectionSuccessfully!");
    }

    @Override
    public void onMessage(String message) {
        JSONObject json = new JSONObject(message);
        if ("group".contains(json.optString("message_type"))){
            MessageForwarder.groupAnalyze(message);
            // System.out.println("[WebSocket-Group] "+json.getString("raw_message"));
        } else if ("private".contains(json.optString("message_type"))){
            MessageForwarder.friendsAnalyze(message);
            // System.out.println("[WebSocket-Friends] "+json.getString("raw_message"));
        } else {
            System.out.println("[WebSocket-MSG] "+json);
        }
    }


    @Override
    public void onClose(int code, String reason, boolean remote) {
        WssReconnectManager.tryReconnect();
    }

    @Override
    public void onError(Exception ex) {
        WssReconnectManager.tryReconnect();
    }

}
