#include "model/Comment.hpp"
#include "core/JsonDecode.hpp"
#include "spec/ModelLimits.hpp"
namespace dp {
Comment::Data Comment::Data::fromJson(const Json& j) {
using D = JsonDecode;
Data d;
d.id = D::req<std::string>(j, "uid");
d.userId = D::req<std::string>(j, "user_uid");
d.content = D::req<std::string>(j, "content");
d.parentId = D::opt<std::string>(j, "parent_uid");
d.targetType = D::req<std::string>(j, "target_type");
d.targetId = D::req<std::string>(j, "target_uid");
d.createdAt = D::reqDate(j, "created_at");
return d;
}
Comment::Votes Comment::Votes::fromJson(const Json& j) {
using D = JsonDecode;
return Votes{D::req<std::int64_t>(j, "up"), D::req<std::int64_t>(j, "down")};
}
Comment Comment::fromJson(const Json& j, std::size_t depth) {
using D = JsonDecode;
if (depth > spec::ModelLimits::kMaxCommentDepth) throw DecodeError("comment tree too deep");
Comment c;
c.data = Data::fromJson(D::child(j, "comment"));
c.author = User::fromJson(D::child(j, "author"));
c.myVote = Vote::fromInt(D::req<std::int64_t>(j, "my_vote"));
c.votes = Votes::fromJson(D::child(j, "votes"));
c.attachments = D::reqModels<Attachment>(j, "attachments");
c.children = D::reqList<Comment>(j, "children", [depth](const Json& item) { return Comment::fromJson(item, depth + 1); });
c.reactions = Reactions::fromJson(D::child(j, "reactions"));
return c;
}
Comment Comment::replacingReactions(const Reactions& newReactions, const std::vector<Comment>& newChildren) const {
Comment out = *this;
out.reactions = newReactions;
out.children = newChildren;
return out;
}
Comment Comment::replacingChildren(const std::vector<Comment>& newChildren) const {
Comment out = *this;
out.children = newChildren;
return out;
}
Comment Comment::applyingVote(Vote newVote, const std::vector<Comment>& newChildren) const {
Comment out = *this;
if (myVote == Vote::Up) --out.votes.up;
else if (myVote == Vote::Down) --out.votes.down;
if (newVote == Vote::Up) ++out.votes.up;
else if (newVote == Vote::Down) ++out.votes.down;
out.myVote = newVote;
out.children = newChildren;
return out;
}
} // namespace dp