using Cinemachine;
using UnityEngine;
using UnityEngine.Serialization;

public class CameraController : MonoBehaviour {
    private const float minFollowYOffset = 2f;
    private const float maxFollowYOffset = 12f;

    [FormerlySerializedAs("MoveSpeed")] [SerializeField]
    private float moveSpeed = 10f;

    [FormerlySerializedAs("RotationSpeed")] [SerializeField]
    private float rotationSpeed = 100f;

    [FormerlySerializedAs("zoomAmount")] [FormerlySerializedAs("ZoomAmount")] [SerializeField]
    private float zoomIncreaseAmount = 1f;

    [FormerlySerializedAs("ZoomSpeed")] [SerializeField]
    private float zoomSpeed = 5f;

    [FormerlySerializedAs("CinemachineVirtualCamera")] [SerializeField]
    private CinemachineVirtualCamera cinemachineVirtualCamera;

    private CinemachineTransposer cinemachineTransposer;
    private Vector3 targetFollowOffset;

    private void Awake() => cinemachineTransposer = cinemachineVirtualCamera.GetCinemachineComponent<CinemachineTransposer>();

    private void Start() => targetFollowOffset = cinemachineTransposer.m_FollowOffset;

    private void Update() {
        HandleMovement();
        HandleRotation();
        HandleZoom();
    }

    private void HandleMovement() {
        Vector2 inputMoveDir = InputManager.Instance.GetCameraMoveVector();
        transform.position += Time.deltaTime * moveSpeed * (transform.forward * inputMoveDir.y + transform.right * inputMoveDir.x);
    }

    private void HandleRotation() {
        Vector3 rotationVector = new() { y = InputManager.Instance.GetCameraRotateAmount() };
        transform.eulerAngles += Time.deltaTime * rotationSpeed * rotationVector;
    }

    private void HandleZoom() {
        targetFollowOffset.y += InputManager.Instance.GetCameraZoomAmount() * zoomIncreaseAmount;
        targetFollowOffset.y = Mathf.Clamp(targetFollowOffset.y, minFollowYOffset, maxFollowYOffset);
        cinemachineTransposer.m_FollowOffset = Vector3.Lerp(cinemachineTransposer.m_FollowOffset, targetFollowOffset, zoomSpeed * Time.deltaTime);
    }
}