/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#pragma once

#include "Scene/SimpleAnimationController.hpp"
#include "Base/Event.hpp"
#include "Base/ITickable.hpp"
#include "Math/Math.hpp"
#include "Math/Pose.hpp"

#include <vector>
#include <utility>
#include <initializer_list>

namespace OpenVulkano::Scene
{
	class SequenceAnimationController : public ITickable 
	{
	public:
		using PoseDurationPair = std::pair<Math::PoseF, double>;
	
	private:
		SimpleAnimationController m_animationController;
		std::vector<PoseDurationPair> m_steps;
		size_t m_currentStep = 0;
		bool m_loop = false;
		double m_resetTime = 0;

		void SequenceCompletedCallback(SimpleAnimationController *animationController);

	public:
		Event<SequenceAnimationController *> OnSequenceCompleted;

		SequenceAnimationController();

		/**
		 * Enables or disables looping of the animation sequence.
		 *
		 * When looping is enabled, the sequence will restart from the first step after the last step is completed.
		 * If the start and end poses of the step list are equal or the reset time is 0, the sequence will jump
		 * directly to the first step. Otherwise, it will animate the transition back to the first step using the
		 * reset time set by the user.
		 *
		 * @param loop A boolean value to enable or disable looping.
		 */
		void EnableLoop(bool value) { m_loop = value; }

		void SetNode(Node *node) { m_animationController.SetNode(node); }
		Node* GetNode() const { return m_animationController.GetNode(); }

		/**
		 * Sets the time to transition back to the first pose when looping is enabled.
		 *
		 * If the reset time is set to 0, the sequence will jump directly to the first step. If the start and end poses
		 * of the step list are equal, the sequence will also jump directly to the first step regardless of the reset time.
		 * Otherwise, the sequence will animate the transition back to the first step using the reset time.
		 *
		 * @param resetTime The time to transition back to the first pose.
		 * @see GetAnimationPoseResetTime
		 */
		void SetAnimationPoseResetTime(double resetTime) { m_resetTime = resetTime; }
		
		/**
		 * Gets the current reset time for transitioning back to the first pose.
		 *
		 * @return The current reset time.
		 * @see SetAnimationPoseResetTime
		 */
		double GetAnimationPoseResetTime() const { return m_resetTime; }

		void Restart();
		bool IsFinished() const;

		void AddAnimationStep(const Math::PoseF &pose, double duration);
		void AddAnimationSteps(std::initializer_list<Math::PoseF> poses, double duration);
		void AddAnimationSteps(std::initializer_list<PoseDurationPair> steps);
		const PoseDurationPair& GetStep(int index) const;
		const std::vector<PoseDurationPair> &GetSteps() const { return m_steps; }

		void Tick() override;
	};
}