#include <nlohmann/json.hpp>
#include <string>

#include "mtx/events/messages/image.hpp"

using json = nlohmann::json;

namespace common = mtx::common;

namespace mtx {
namespace events {
namespace msg {

void
from_json(const json &obj, Image &content)
{
        content.body    = obj.value("body", "");
        content.msgtype = obj.at("msgtype");

        content.url = obj.value("url", "");

        if (obj.find("info") != obj.end())
                content.info = obj.at("info").get<common::ImageInfo>();

        if (obj.find("file") != obj.end())
                content.file = obj.at("file").get<crypto::EncryptedFile>();

        if (obj.count("m.relates_to") != 0)
                content.relates_to = obj.at("m.relates_to").get<common::ReplyRelatesTo>();
}

void
to_json(json &obj, const Image &content)
{
        obj["msgtype"] = "m.image";
        obj["body"]    = content.body;
        obj["url"]     = content.url;
        obj["info"]    = content.info;

        if (content.file)
                obj["file"] = content.file.value();

        if (!content.relates_to.in_reply_to.event_id.empty())
                obj["m.relates_to"] = content.relates_to;
}

void
from_json(const json &obj, StickerImage &content)
{
        content.body = obj.value("body", "");

        content.url = obj.value("url", "");

        if (obj.find("info") != obj.end())
                content.info = obj.at("info").get<common::ImageInfo>();

        if (obj.find("file") != obj.end())
                content.file = obj.at("file").get<crypto::EncryptedFile>();

        if (obj.count("m.relates_to") != 0)
                content.relates_to = obj.at("m.relates_to").get<common::ReplyRelatesTo>();
}

void
to_json(json &obj, const StickerImage &content)
{
        obj["body"] = content.body;
        obj["url"]  = content.url;
        obj["info"] = content.info;

        if (content.file)
                obj["file"] = content.file.value();

        if (!content.relates_to.in_reply_to.event_id.empty())
                obj["m.relates_to"] = content.relates_to;
}

} // namespace msg
} // namespace events
} // namespace mtx
