//
// Created by Ht on 2022/10/24.
//

#ifndef IOT_EDGE_VDALNEW_QVDALJEDPDEBUGGER_H
#define IOT_EDGE_VDALNEW_QVDALJEDPDEBUGGER_H

#include <jedp/jedp.h>
#include <qlibc/cmd/JCArgNode.h>
#include <exlib/QJAServer.h>
#include <exlib/QJAService.h>
#include "JARemoteCommandor.h"

namespace jedge {

    /**
     * 用于单步控制,记录和转发log
     */

#define DEFAULT_TIMEOUT_TIME 15

    class JE_API QVdalJedpDebugger :
            public JARemoteCommandor {
    public:
        QJAMgService &service_;
        std::string  debug_src_;    //远程调试端口,超时自动清理
        std::string  debug_svc_;    //远程调试端口,超时自动清理
        std::string  debug_uri_;    //远程调试端口,超时自动清理
        int          debug_key_ = -1;    //调试的key
    protected:
        qlibc::QRTimer timer_;      //超时清理器
        std::recursive_mutex   m_;
        bool quit_ = false;
        int  timeout_ = DEFAULT_TIMEOUT_TIME;          //  = 15 S 同步
        QStringList  log_stack_;

    public:
        explicit QVdalJedpDebugger(QJAMgServer& opr, QJAMgService& service);
        ~QVdalJedpDebugger() override;

        void buildCommandHandlers() override;

        void clearTimeoutDebugSource();

        //本地调命令: jedp <name> show / load / list /add / remove
        bool handleDebugCommand(qlibc::JCArgNode &node) {
            QDHLog("jedp debug command : %s", node.toJSONString(true).c_str());
            auto cmd = node.getParam(1);
            return handleCommandorCommand(cmd , node, nullptr);
        }

        void emptyLogs();

        bool bindDebugSource(qlibc::QData&req, qlibc::QData *resp);

        bool removeDebugSource();

        //是否把log转发或本地显示。
        // level : 0 = log, 1 = HLog, 2 = Warn, 3 = EMark, 4 = Err, ...
        void debugLog(const char* log, int level = 0, const char* logKey = nullptr);

        void postSingleLog(const std::string& log);
    };

}

#endif //IOT_EDGE_VDALNEW_QVDALJEDPDEBUGGER_H
