#pragma once

#ifdef NETWORK
#ifdef EMSCRIPTEN

#include <emscripten/websocket.h>
#include "WebSocketClientBase.h"
#include <queue>
#include <mutex>
#include <string>

namespace ZL {

    class WebSocketClientEmscripten : public WebSocketClientBase {
    private:
        EMSCRIPTEN_WEBSOCKET_T socket_ = 0;
        bool connected = false;

        // Очередь для хранения сырых строк от браузера
        std::queue<std::string> messageQueue;

        std::queue<std::string> outgoingQueue;
        std::mutex outgoingMutex;
        void flushOutgoingQueue();

    public:
        WebSocketClientEmscripten() = default;
        virtual ~WebSocketClientEmscripten() = default;

        void Connect(const std::string& host, uint16_t port) override;
        void Disconnect() override;
        void Send(const std::string& message) override;
        void Poll() override;

        bool IsConnected() const override { return connected; }

        // Статические методы-переходники для C-API Emscripten
        static EM_BOOL onOpen(int eventType, const EmscriptenWebSocketOpenEvent* e, void* userData);
        static EM_BOOL onMessage(int eventType, const EmscriptenWebSocketMessageEvent* e, void* userData);
        static EM_BOOL onError(int eventType, const EmscriptenWebSocketErrorEvent* e, void* userData);
        static EM_BOOL onClose(int eventType, const EmscriptenWebSocketCloseEvent* e, void* userData);
    };
}
#endif
#endif

