#include "ros_bridge/include/CasePacker.h"

const char* ROSBridge::CasePacker::topicKey         = "topic";
const char* ROSBridge::CasePacker::messageTypeKey   = "messageType";

ROSBridge::CasePacker::CasePacker()
{

}

bool ROSBridge::CasePacker::showTag(const ROSBridge::CasePacker::JsonDoc &doc, Tag &tag)
{
    if( !_getTopic(doc, tag.topic()) )
        return false;
    if( !_getMessageType(doc, tag.messageType()) )
        return false;
    return true;
}

void ROSBridge::CasePacker::_addTag(JsonDoc &doc, const std::string &topic, const std::string &messageType)
{
    using namespace ROSBridge;
    using namespace rapidjson;

    {
    // add topic
    rapidjson::Value key(CasePacker::topicKey, doc.GetAllocator());
    rapidjson::Value value(topic.c_str(), doc.GetAllocator());
    doc.AddMember(key, value, doc.GetAllocator());
    }

    // add messageType
    rapidjson::Value key(CasePacker::messageTypeKey, doc.GetAllocator());
    rapidjson::Value value(messageType.c_str(), doc.GetAllocator());
    doc.AddMember(key, value, doc.GetAllocator());
}

void ROSBridge::CasePacker::_removeTag(JsonDoc &doc)
{
    using namespace ROSBridge;
    using namespace rapidjson;
    if ( doc.HasMember(CasePacker::topicKey) )
        doc.RemoveMember(CasePacker::topicKey);
    if ( doc.HasMember(CasePacker::messageTypeKey) )
        doc.RemoveMember(CasePacker::messageTypeKey);
}

bool ROSBridge::CasePacker::_getTopic(const ROSBridge::CasePacker::JsonDoc &doc, std::string &topic)
{
    if (!doc.HasMember(CasePacker::topicKey) || !doc[CasePacker::topicKey].IsString())
        return false;
    topic = doc[CasePacker::topicKey].GetString();
    return true;
}

bool ROSBridge::CasePacker::_getMessageType(const ROSBridge::CasePacker::JsonDoc &doc, std::string &messageType)
{
    if (!doc.HasMember(CasePacker::messageTypeKey) || !doc[CasePacker::messageTypeKey].IsString())
        return false;
    messageType = doc[CasePacker::messageTypeKey].GetString();
    return true;
}
