#include "AnimationTree.hpp"

AnimationTreeComponent::AnimationTreeComponent()
	: treeName()
	, enabled(true)
	, useRootMotion(false)
	, dirty(true)
	, treeVersion(0)
{
}

nlohmann::json animationTreeNodeToJson(const AnimationTreeNode &node)
{
	nlohmann::json json;
	json["type"] = node.type;
	if (!node.name.empty())
		json["name"] = node.name;
	if (!node.animationName.empty())
		json["animationName"] = node.animationName;
	if (node.speed != 1.0f)
		json["speed"] = node.speed;
	if (node.fadeSpeed != 7.5f)
		json["fadeSpeed"] = node.fadeSpeed;
	if (!node.endTransitions.empty()) {
		nlohmann::json trans = nlohmann::json::object();
		for (const auto &pair : node.endTransitions)
			trans[pair.first] = pair.second;
		json["endTransitions"] = trans;
	}
	if (!node.children.empty()) {
		json["children"] = nlohmann::json::array();
		for (const auto &child : node.children)
			json["children"].push_back(animationTreeNodeToJson(child));
	}
	return json;
}

void animationTreeNodeFromJson(AnimationTreeNode &node,
			       const nlohmann::json &json)
{
	node.type = json.value("type", "animation");
	node.name = json.value("name", "");
	node.animationName = json.value("animationName", "");
	node.speed = json.value("speed", 1.0f);
	node.fadeSpeed = json.value("fadeSpeed", 7.5f);
	node.endTransitions.clear();
	if (json.contains("endTransitions") &&
	    json["endTransitions"].is_object()) {
		for (auto it = json["endTransitions"].begin();
		     it != json["endTransitions"].end(); ++it)
			node.endTransitions[it.key()] = it.value();
	}
	node.children.clear();
	if (json.contains("children") && json["children"].is_array()) {
		for (const auto &childJson : json["children"]) {
			AnimationTreeNode child;
			animationTreeNodeFromJson(child, childJson);
			node.children.push_back(child);
		}
	}
}
