#include "AnimationTree.hpp"
#include "../ui/ComponentRegistration.hpp"
#include "../ui/AnimationTreeEditor.hpp"
#include "../systems/AnimationTreeRegistry.hpp"
#include "Transform.hpp"

static Ogre::String createDefaultTree()
{
	AnimationTreeNode root;
	root.type = "output";
	root.speed = 1.0f;

	AnimationTreeNode sm;
	sm.type = "stateMachine";
	sm.name = "main";
	sm.fadeSpeed = 7.5f;

	AnimationTreeNode state;
	state.type = "state";
	state.name = "idle";

	AnimationTreeNode anim;
	anim.type = "animation";
	anim.animationName = "idle";

	state.children.push_back(anim);
	sm.children.push_back(state);
	root.children.push_back(sm);

	AnimationTreeRegistry &reg = AnimationTreeRegistry::getSingleton();
	Ogre::String name = reg.generateUniqueName("default");

	AnimationTreeRegistry::AnimationTreeDefinition def;
	def.name = name;
	def.root = root;
	reg.registerTree(def);

	return name;
}

REGISTER_COMPONENT_GROUP("Animation Tree", "Rendering",
				 AnimationTreeComponent, AnimationTreeEditor)
{
	registry.registerComponent<AnimationTreeComponent>(
		"Animation Tree", "Rendering",
		std::make_unique<AnimationTreeEditor>(sceneMgr),
		/* Adder */
		[sceneMgr](flecs::entity e) {
			if (!e.has<TransformComponent>()) {
				TransformComponent transform;
				transform.node =
					sceneMgr->getRootSceneNode()
						->createChildSceneNode();
				e.set<TransformComponent>(transform);
			}
			AnimationTreeComponent at;
			at.treeName = createDefaultTree();
			at.dirty = true;
			e.set<AnimationTreeComponent>(at);
		},
		/* Remover */
		[sceneMgr](flecs::entity e) {
			(void)sceneMgr;
			e.remove<AnimationTreeComponent>();
		});
}
