using System;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Conjure.Input
{
    public class InputManagerClient: SerializedMonoBehaviour
    {
        [SerializeField, FoldoutGroup("Debug"), ReadOnly]
        private InputVariablePlayersReference _inputVariablePlayersReference;
        [SerializeField, FoldoutGroup("Debug"), ReadOnly]
        private InputActionAsset _inputActionAsset;
        [SerializeField, FoldoutGroup("Debug"), ReadOnly]
        private PlayerEnum _player;
        [SerializeField, FoldoutGroup("Debug"), ReadOnly]
        private InputAction _moveAction;
        [SerializeField, FoldoutGroup("Debug"), ReadOnly]
        private InputAction _primaryAction;
        
        public void Constructor(InputActionAsset inputActionAsset, InputVariablePlayersReference inputVariablePlayersReference, PlayerEnum player)
        {
            if (player == PlayerEnum.None)
            {
                throw new PlayerEnumNoneException();
            }
            
            _inputActionAsset = inputActionAsset;
            _inputVariablePlayersReference = inputVariablePlayersReference;
            _player = player;
            
            _moveAction = _inputActionAsset.FindAction("Move");
            _moveAction.started += OnMove;
            _moveAction.performed += OnMove;
            _moveAction.canceled += OnMove;
            
            _primaryAction = _inputActionAsset.FindAction("PrimaryAction");
            _primaryAction.started += OnPrimaryAction;
        }

        private void OnMove(InputAction.CallbackContext context)
        {
            if (_player == PlayerEnum.None)
            {
                return;
            }
            
            Vector2 direction = context.action.ReadValue<Vector2>();
            _inputVariablePlayersReference.GetReferenceByPlayerEnum(_player).MovementDirectionVariable.Value = new Vector3(direction.x, 0, direction.y);
        }

        private void OnPrimaryAction(InputAction.CallbackContext context)
        {
            if (_player == PlayerEnum.None)
            {
                return;
            }
            
            if (context.action.ReadValue<float>().Equals(1f))
            {
                _inputVariablePlayersReference.GetReferenceByPlayerEnum(_player).PrimaryButton.Raise();
            }
        }

        private void OnDestroy()
        {
            _moveAction.started -= OnMove;
            _moveAction.performed -= OnMove;
            _moveAction.canceled -= OnMove;
        }
    }
}