//
// Created by Ht on 2022/1/17.
//

#ifndef INC_0_LIBDEVCPP_QOBJECTEVENTHOLDER_H
#define INC_0_LIBDEVCPP_QOBJECTEVENTHOLDER_H


#include <jebase/config.h>
#include <functional>
#include "QPObjectHolder.h"
#include "QData.hpp"

namespace qlibc {

    using QObjectEventHandler = std::function<void( qlibc::QData& msg )>;

    class JE_API QObjectEventHolder {
    protected:
        qlibc::QSharedObjectHolder<QObjectEventHandler>* mEventHandlers = nullptr;
        qlibc::QSharedObjectHolder<QObjectEventHandler>& getEventHolder() {
            if(mEventHandlers== nullptr) {
                mEventHandlers = new qlibc::QSharedObjectHolder<QObjectEventHandler>();
            }
            return *mEventHandlers;
        }

        void invokeEvent(const std::string &event, qlibc::QData& msg);

        void markObjectEvent(const std::string &event); //定义支持的event类型，只有在支持事件类型中的事件，才可能被set和invoke

        void releaseEventHandlers() {
            if(mEventHandlers!=nullptr){
                mEventHandlers->releaseAll();
                delete mEventHandlers;
                mEventHandlers = nullptr;
            }
        }
    public:
        inline void getEventsList(QStringList& kl) {
            getEventHolder().getKeySets(kl);
        }

        virtual ~QObjectEventHolder() { releaseEventHandlers(); }

        void setEventHandler(const std::string& event, const QObjectEventHandler &handler);

    };
}

#endif //INC_0_LIBDEVCPP_QOBJECTEVENTHOLDER_H
