using System;
using State;
using State.PawnStateMachine;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Player
{
    [RequireComponent(typeof(PlayerInput))]
    public class InputRouter : MonoBehaviour
    {
        private PlayerInput _playerInput;
        private PawnStateMachine pawnStateMachine;
        private InputActionMap _map;
        
        private void Awake()
        {
            _playerInput = GetComponent<PlayerInput>();
            pawnStateMachine = GetComponent<PawnStateMachine>();
            _map = _playerInput.actions.FindActionMap("Player", throwIfNotFound: true);
        }

        private void OnEnable()
        {
            _map["Move"].performed += OnMovePerformed;
            _map["Move"].canceled += OnMoveCanceled;
            _map["Attack"].performed += OnAttackPerformed;
            _map["Jump"].performed += OnJumpPerformed;
            _map["Pause"].performed += OnPausePerformed;
        }

        private void OnDisable()
        {
            _map["Move"].performed -= OnMovePerformed;
            _map["Move"].canceled -= OnMoveCanceled;
            _map["Attack"].performed -= OnAttackPerformed;
            _map["Jump"].performed -= OnJumpPerformed;
            _map["Pause"].performed -= OnPausePerformed;
        }
        
        private void OnJumpPerformed(InputAction.CallbackContext obj)
        {
            pawnStateMachine.Issue(GameState.Command.Jump);
        }

        private void OnPausePerformed(InputAction.CallbackContext obj)
        {
            throw new NotImplementedException();
        }

        private void OnAttackPerformed(InputAction.CallbackContext obj)
        {
            pawnStateMachine.Issue(GameState.Command.Attack);
        }

        private void OnMoveCanceled(InputAction.CallbackContext obj)
        {
            pawnStateMachine.SetMove(Vector2.zero);
        }

        private void OnMovePerformed(InputAction.CallbackContext obj)
        {
            pawnStateMachine.SetMove(obj.ReadValue<Vector2>());
        }
    }
}