

#include <WHISPER/Messages/Message.hpp>
#include <memory>




namespace WHISPER {
    Message::Message(std::string stringMessage)
    {
        msg = messages::header::Message();
        try {
            msg.ParseFromString(stringMessage);

            deviceId_ = msg.sourceid();
            topic_ = msg.topic();
            sourceType_ = msg.sourcetype();
            msgType_ = msg.msgtype();
            parentId_ = msg.parentid();


        } catch (const std::exception& e) {
            LOG_S(ERROR)<<e.what();
        }


    }


     Message::Message(std::uint32_t parentId,std::uint32_t deviceId, MsgTopics topic, MsgType Type,SourceType src):
     parentId_(parentId),deviceId_(deviceId),topic_(topic),sourceType_(src),msgType_(Type)
     {
        msg =  messages::header::Message();

        if(msg.IsInitialized())
        {
            msg.set_sourceid(deviceId);
            msg.set_topic(topic);
            msg.set_sourcetype(sourceType_);
            msg.set_msgtype(msgType_);
            msg.set_parentid(parentId);

        }
        
     }



    std::string Message::getPayloadString()
    {
        return payloadString_;
    }

     messages::header::Message Message::getProtoMessage()
      {
        return msg;
      }


     void Message::addPayLoad(std::shared_ptr<google::protobuf::Any> payload)
     {
        payload_ = payload;
        payloadString_ = payload->SerializeAsString();

        msg.clear_payload();
        msg.mutable_payload()->CopyFrom(*payload);
        // msg.add_payload()->CopyFrom(*payload_);

    }




    std::string Message::serialize()
    {

            std::string serializedMessage;
            if (msg.IsInitialized()) {
                serializedMessage = msg.SerializeAsString();
            }
            return serializedMessage;
    }


}