#pragma once

#include "mqtt_basic.hpp"
#include "mqtt_client.hpp"

#include <google/protobuf/message_lite.h>

namespace mqtt_dataio
{

    template <typename T>
    class publisher : public publisher_basic
    {

    public:
        publisher() = delete;
        publisher(const publisher &) = delete;

        publisher(const std::string &name)
            : __m_name(name)
        {
            std::cout << "create publisher topic: " << __m_name << std::endl;
        }

        ~publisher() override
        {
            std::cout << "destroy publisher topic: " << __m_name << std::endl;
        }

        // void publish(const T &msg)
        // {
        //     if constexpr (std::is_base_of<google::protobuf::MessageLite, T>::value)
        //     {
        //         std::string data;
        //         if (msg.SerializeToString(&data))
        //         {
        //             std::vector<uint8_t> buff(data.begin(), data.end());
        //             mqtt_dataio::client::ins().publish(__m_name, buff);
        //         }
        //         else
        //         {
        //             std::cout << "SerializeToString failed!!!" << std::endl;
        //         }
        //     }

        //     if constexpr (!std::is_base_of<google::protobuf::MessageLite, T>::value)
        //     {
        //         mqtt_dataio::client::ins().publish(__m_name, msg);
        //     }
        // }

        // std::enable_if<!std::is_base_of<google::protobuf::MessageLite, T>::value, const T &>::type
        // typename std::enable_if<!std::is_base_of<google::protobuf::MessageLite, T>::value>::type
        template<typename U = T, typename std::enable_if<!std::is_base_of<google::protobuf::MessageLite, U>::value, int>::type = 0>
        void publish(const T& msg)
        {
            mqtt_dataio::client::ins().publish(__m_name, msg);
        }

        // std::enable_if<std::is_base_of<google::protobuf::MessageLite, T>::value, const T &>::type
        // typename std::enable_if<std::is_base_of<google::protobuf::MessageLite, T>::value>::type
        template<typename U = T, typename std::enable_if<std::is_base_of<google::protobuf::MessageLite, U>::value, int>::type = 0>
        void publish(const google::protobuf::MessageLite& msg)
        {
            std::string data;
            if (msg.SerializeToString(&data))
            {
                std::vector<uint8_t> buff(data.begin(), data.end());
                mqtt_dataio::client::ins().publish(__m_name, buff);
            }
            else
            {
                std::cout << "SerializeToString failed!!!" << std::endl;
            }
        }


    private:
        std::string __m_name;
    };

}

