//
// Created by Ht on 2021/12/19.
//

#ifndef INC_0_LIBDEVCPP_QJAMGUTILS_H
#define INC_0_LIBDEVCPP_QJAMGUTILS_H


#include <qlibc/QData.hpp>
#include <qlibc/QPObjectHolder.h>
#include <mgbus/ChannelOperator.h>

namespace jedge {
    using UriMessageHandler = std::function<bool(jedge::ChannelOperator &o, const std::string &u,
                                                 qlibc::QData &m)>;

    class UriHandlerHolder {
    protected:
        ChannelOperator &opr_;
        qlibc::QSharedObjectHolder<UriMessageHandler> ud_handlers_;

    public:
        explicit UriHandlerHolder(ChannelOperator &o) : opr_(o) {}

        void releaseUdHandlers() {
            ud_handlers_.releaseAll();
        }

        void addHandler(const std::string &uri, const UriMessageHandler &handler) {
            ud_handlers_.appendNew(uri, new UriMessageHandler(handler));
        }

        bool handleMessage(const std::string &uri, qlibc::QData &message) {
            auto handler = ud_handlers_.findObject(uri);
            if (handler != nullptr) {
                try {
                    return handler->operator()(opr_, uri, message);
                } catch (std::bad_function_call &e) {}
            }
            return false;
        }
    };
}

#endif //INC_0_LIBDEVCPP_QJAMGUTILS_H
