//
// Created by Ht on 2021/8/1.
//

#ifndef INC_0_LIBDEVCPP_NEW_JA_QSOCKCLIENT_H
#define INC_0_LIBDEVCPP_NEW_JA_QSOCKCLIENT_H

#include <mgbus/ChannelOperator.h>
#include <mgbus/MgDataChannel.h>
#include <mgbus/QJsonSocketClient.h>
#include <jadom2/JAUtil.h>

namespace jedge {

    static const char* sval_event_connect = "onConnect";
    static const char* sval_event_timeout = "onTimeout";

    class JE_API QSockClient :
            public jedge::QJsonSocketClient {
    protected:
        qlibc::QSharedObjectHolder<jedge::JsonSocketRequestUDHandler>* client_ud_handlers_ = nullptr;
        qlibc::QRTimer  heart_timer_ = nullptr;
        QByte  tick = 0;

    public:
        explicit QSockClient(ChannelOperator& manager, const std::string& name = jedge::DATA_CHANNEL_SOCK) :
                QJsonSocketClient(manager, name)  {
            markObjectEvent(sval_event_connect);
            markObjectEvent(sval_event_timeout);
        };

        ~QSockClient() override;

        bool addUriHandler(const string &pattern, const JsonSocketRequestUDHandler& handler);

        bool checkSocketMessageLegal(qlibc::QData &data) override;

        bool deliverClientMessage(ChannelOperator &opr, qlibc::QData &message);

        bool connect(const std::string &host, int port, SocketMode mode);

        void heart_beat();

        void onClientTimeout();

        bool postSocketRequest(const string &uri, qlibc::QData &req, qlibc::QData &rsp, int timeout);
    };

}

#endif //INC_0_LIBDEVCPP_NEW_JA_QSOCKCLIENT_H
