using System;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Boxfriend.Input
{
    public class InputDispatcher : MonoBehaviour
    {
        public event Action<Vector2> OnMove;
        public event Action<Vector2> OnLook;
        public event Action<bool> OnSprint;
        public event Action<bool> OnCrouch;
        public event Action OnJump;
        public event Action OnInteract;

        private InputActionMap _inputActions;

        private void Awake()
        {
            _inputActions = InputSystem.actions.FindActionMap(ConstantStrings.PlayerActionMap);

            Subscribe();
        }

        private void Subscribe()
        {
            _inputActions.FindAction(ConstantStrings.InteractInput).performed += _ => OnInteract?.Invoke();

            _inputActions.FindAction(ConstantStrings.JumpInput).performed += _ => OnJump?.Invoke();

            _inputActions.FindAction(ConstantStrings.MoveInput).performed += ctx => OnMove?.Invoke(ctx.ReadValue<Vector2>());
            _inputActions.FindAction(ConstantStrings.MoveInput).canceled += ctx => OnMove?.Invoke(ctx.ReadValue<Vector2>());

            _inputActions.FindAction(ConstantStrings.LookInput).performed += ctx => OnLook?.Invoke(ctx.ReadValue<Vector2>());

            _inputActions.FindAction(ConstantStrings.SprintInput).performed += ctx => OnSprint?.Invoke(ctx.ReadValueAsButton());
            _inputActions.FindAction(ConstantStrings.SprintInput).canceled += ctx => OnSprint?.Invoke(ctx.ReadValueAsButton());

            _inputActions.FindAction(ConstantStrings.CrouchInput).performed += ctx => OnCrouch?.Invoke(ctx.ReadValueAsButton());
            _inputActions.FindAction(ConstantStrings.CrouchInput).canceled += ctx => OnCrouch?.Invoke(ctx.ReadValueAsButton());
        }

        private void OnEnable () => _inputActions.Enable();
        private void OnDisable () => _inputActions.Disable();
        private void OnDestroy () => _inputActions.Dispose();
    }
}
