#ifndef _WEBSOCKET_PROTOCOL_H_
#define _WEBSOCKET_PROTOCOL_H_


#include "protocol.h"

#include <web_socket.h>
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <mutex>

#define WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT (1 << 0)

class WebsocketProtocol : public Protocol {
public:
    WebsocketProtocol();
    ~WebsocketProtocol();

    void SetPrimary(bool primary);// 设置是否为主要连接协议
    void Start() override;
    void SendAudio(const std::vector<uint8_t>& data) override;
    bool OpenAudioChannel() override;
    void CloseAudioChannel() override;
    bool IsAudioChannelOpened() const override;

private:
    EventGroupHandle_t event_group_handle_;
    WebSocket* websocket_ = nullptr;
    static std::atomic<int> pending_delete_tasks_;  // 待删除任务计数
    std::mutex websocket_mutex_;  // WebSocket操作互斥锁
    bool is_being_deleted_ = false;  // 删除状态标志
    bool is_primary_ = true;// 是否为主要连接协议

    void ParseServerHello(const cJSON* root);
    void SendText(const std::string& text) override;
};

#endif
