/**
 * API接口 engine
 * */

#ifndef INC_WSServerEngine_H
#define INC_WSServerEngine_H

#include <arpa/inet.h>
#include "AppCommon.h"

#include "EngineBase.h"
#include "EngineFactory.h"
#include "json/json.h"
#include "websocket.h"

class WSServerEngine : public ai_matrix::EngineBase
{
public:
    WSServerEngine();
    ~WSServerEngine();

    APP_ERROR Init() override;
    APP_ERROR DeInit() override;
    APP_ERROR Process() override;

    struct CMDConnData
    {
        bool login;
        std::string ip;
    };

    using WSServer = websocket::WSServer<WSServerEngine, CMDConnData>;
    using WSConn = WSServer::Connection;

    void onWSSegment(WSConn &conn, uint8_t opcode, const uint8_t *payload, uint32_t pl_len, uint32_t pl_start_idx,
                     bool fin);
    void onWSMsg(WSConn &conn, uint8_t opcode, const uint8_t *payload, uint32_t pl_len);
    void onWSClose(WSConn &conn, uint16_t status_code, const char *reason);
    bool onWSConnect(WSConn &conn, const char *request_uri, const char *host, const char *origin, const char *protocol,
                     const char *extensions, char *resp_protocol, uint32_t resp_protocol_size, char *resp_extensions,
                     uint32_t resp_extensions_size);
    void stop();
    std::string onCMD(CMDConnData &conn, int argc, const char **argv);

    void sendAllClient(const std::string& msg);

protected:

private:
    std::string strPort0_;
    std::string strPort1_;

    ai_matrix::WSocketConfig wsServerConfig_;

    WSServer wsserver_;
    std::thread ws_thr_;
    int listenfd_;
    std::atomic<bool> running_;

    std::thread broadcastThread_;

};

ENGINE_REGIST(WSServerEngine)

#endif
