//
// Created by Ht on 2021/9/26.
//

#ifndef INC_0_LIBDEVCPP_CPAD_MGBUSNODESERVICE_H
#define INC_0_LIBDEVCPP_CPAD_MGBUSNODESERVICE_H

#include "MgbusServerService.h"
#include <mgbus/MgbusNode.h>
#include <mgbus/MgTriggerManager.h>

namespace jedge {

    /**
     *  发给mgs为目标的指令，通过本节点代码，发送
     */

    class JE_API MgbugServerLocalNode : public MgNode {
    protected:
        MgBusServer& server_;
    public:
        explicit MgbugServerLocalNode(MgBusServer& server) : MgNode(JEDGE_MGBUS_MODUAL_MGS_SERVER), server_(server)
        {}

        bool postMessage(qlibc::QData &datamsg) override;

        bool postMessage(const std::string &datamsg) override;

        void closeNode() override;

        const string &sockKey() override;

        bool timeout(QByte max_tick) override;
    };

    class JE_API MgbusNodeService :
            public MgbusServerService {
    protected:
        qlibc::QSharedObjectHolder<MgNode>  key_nodes_;

    public:
        explicit MgbusNodeService(jedge::MgBusServer &opr, const std::string &name, const qlibc::QData& config);

        ~MgbusNodeService() override = default;

        void releaseNodes() override {
            key_nodes_.releaseAll();    //not release.
        }

        inline void iterateNode(const qlibc::QSharedObjectHolder<MgNode>::SharedObjAccessor & accessor) {
            key_nodes_.invokeOnAllObject(accessor, true);
        }

        void onServiceStart(const qlibc::QData &config) override;

        void onServiceStop() override;

        std::shared_ptr<MgNode> findNode(const std::string &nodeKey) override {
            return key_nodes_.findObject(nodeKey);
        }

        bool reIndexNode(const string &nodeKey, const string &newKey) override;

        void removeNode(const std::string &nodeKey) override;

        void addNode(const std::string &nodeKey, MgNodeRef& node) override;

        bool postMessageToMgMode(const std::string &dest_short, qlibc::QData &data);

        void broadCastMgbusMessage(qlibc::QData &datamsg, bool toSelf = false);

        bool singleCastMgbusMessage(const std::string &dest, qlibc::QData &message);

        bool existsNode(const std::string &nodeKey) override;

        void trigExistsModules(jedge::MgEvent& event, jedge::MgTriggerWatcher &watcher);

        void checkMainKeyFree(const string &nodeKey) override;

        void listMgbusNodes(QStringList &nodeList);

        int LoggedNodeSize();

        void invokeNodeOnOfflineEvent(const std::string &event, const std::string &nodeKey);

        void tryShiftMultiLoginModuleAsMain(const std::string &mainKey);

    protected:
        bool tryResetMainKey(std::string &newKey, const std::string &currentKey);
    };
}


#endif //INC_0_LIBDEVCPP_CPAD_MGBUSNODESERVICE_H
