using System;
using CameraScripts;
using UnityEngine;

namespace Animators.Leonid_Animator.Player
{
    public class InputHandler : MonoBehaviour
    {
        public float horizontal;
        public float vertical;
        public float moveAmount;
        public float mouseX;
        public float mouseY;

        public bool crouchPressed;
        public bool jumpPressed;
        public bool firePressed;

        private ThirdPersonViewInput _inputActions;
        private Vector2 _movementInput;
        private Vector2 _cameraInput;

        private CameraHandler _cameraHandler;

        private void Start()
        {
            _cameraHandler = CameraHandler.Singleton;
            if (_cameraHandler == null)
                Debug.LogError("Camera Handler not found");
        }

        private void Update()
        {
            _cameraHandler.TargetPosition(Time.deltaTime);
            _cameraHandler.HandleCameraRotation(Time.deltaTime, mouseX, mouseY);
        }

        private void OnEnable()
        {
            if (_inputActions is null)
            {
                _inputActions = new ThirdPersonViewInput();
                _inputActions.PlayerMovement.Movement.performed +=
                    context => _movementInput = context.ReadValue<Vector2>();
                _inputActions.PlayerMovement.Camera.performed +=
                    context => _cameraInput = context.ReadValue<Vector2>();
                _inputActions.PlayerActions.Crouch.performed +=
                    context => crouchPressed = true;
                _inputActions.PlayerActions.Jump.performed +=
                    context => jumpPressed = true;
                _inputActions.PlayerActions.Fire.performed +=
                    context => firePressed = true;
                _inputActions.PlayerActions.Fire.canceled +=
                    context => firePressed = false;
            }
            _inputActions.Enable();
        }

        private void OnDisable()
        {
            _inputActions.Disable();
        }

        public void TickInput(float delta)
        {
            MoveInput(delta);
        }

        private void MoveInput(float delta)
        {
            horizontal = _movementInput.x;
            vertical = _movementInput.y;
            moveAmount = Mathf.Clamp01(Mathf.Abs(horizontal) + Mathf.Abs(vertical));
            mouseX = _cameraInput.x;
            mouseY = _cameraInput.y;
        }
    }
}