//
// Created by Ht on 2020/5/10.
//

#ifndef TESTBIN_MGBUSJSONCLIENT_H
#define TESTBIN_MGBUSJSONCLIENT_H


#include <unordered_map>
#include <regex>
#include <qlibc/qlibc.h>
#include "SocketClient.h"
#include "SocketBuffer.h"
#include "SocketHandlerHolder.h"
#include "MgbusProtocol.h"

namespace jedge {

    class JE_API QJsonSocketClient :
            public SocketClient {

    protected:
        SocketHandlerHolder handlers_;

        SocketBuffer buffer_;
        DataDivider  devider_;

        JsonSocketHandler* msg_pre_handler_ = nullptr;

        virtual void doHandleStrData(const string &msgStr);

    public:
        explicit QJsonSocketClient(ChannelOperator& opr , const string& modulename, const char* dividerChars = default_devicer_char_) :
                SocketClient(opr, modulename), handlers_(opr), devider_(dividerChars) {
        }

        ~QJsonSocketClient() override {
            delete msg_pre_handler_;
            msg_pre_handler_ = nullptr;
        }

        void setPrintIncomingStr(bool print) override;;

        void clearDefaultHandler() {
            handlers_.clearDefaultHandler();
        }

        bool handleSocketData(const char *buff, int len, SocketMode mode) override;

        void setMessageHook(const JsonSocketHandler& hook);

        bool Uri(const string &uri, const JsonSocketHandler& handler);      //添加特定uri的handler，优先级较高

        bool Regex(const string &pattern, const JsonSocketHandler& handler);        //添加模式uri的handler

        void DefaultHandler(const JsonSocketHandler& handler);                   //添加默认的消息处理
        void UnhandleHandler(const JsonSocketHandler& handler);                   //添加默认的未处理消息处理响应函数

        bool postRawMessage(qlibc::QData &message) override;

        void clearRegex(const string &pattern = "");

        virtual bool checkSocketMessageLegal(qlibc::QData &data);
    };

}


#endif //TESTBIN_MGBUSJSONCLIENT_H
