/*
 * 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/.
 */

#include "MorphableCameraController.hpp"
#include "Base/FrameMetadata.hpp"
#include "Input/InputManager.hpp"
#include "Input/InputKey.hpp"
#include "Scene/Camera.hpp"

namespace OpenVulkano::Scene
{
	MorphableCameraController::MorphableCameraController(MorphableCamera* camera)
	    : CameraController(camera)
	    , m_animationDuration(1.0f)
	    , m_currentTime(0.0f)
	    , m_isMorphing(false)
	    , m_targetMorphStatePerspective(true)
	{}

	void MorphableCameraController::Init(MorphableCamera* camera)
	{
		CameraController::Init(camera);
	}

	void MorphableCameraController::Tick()
	{

		if (m_isMorphing)
		{
			m_currentTime += CURRENT_FRAME.frameTime;
			if (m_currentTime > m_animationDuration) m_currentTime = m_animationDuration;
			float t = m_currentTime / m_animationDuration;
			if (t >= 1.0f)
			{
				t = 1.0f;
				m_isMorphing = false;
			}
			const float newState = m_targetMorphStatePerspective ? (1.0f - t) : t;
			static_cast<MorphableCamera*>(GetCamera())->SetMorphState(newState);
		}
	}

	void MorphableCameraController::SetTargetState(const bool toPerspective)
	{
		if (toPerspective == m_targetMorphStatePerspective) return;
		m_targetMorphStatePerspective = toPerspective;
		m_isMorphing = true;
	}

	MorphableCameraControllerWithInput::MorphableCameraControllerWithInput(MorphableCamera* camera)
		: m_controller(camera)
		, m_actionMorph(Input::InputManager::GetInstance()->GetAction("morph"))
	{
		m_actionMorph->BindKey(Input::InputKey::Keyboard::KEY_P);
	}

	void MorphableCameraControllerWithInput::Tick()
	{
		if (Input::InputManager::GetInstance()->GetButtonDown(m_actionMorph))
		{
			SetTargetState(!m_controller.IsTargetPerspective());
			m_controller.Reset();
		}
		m_controller.Tick();
	}
}
