using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : BasicCharacter {
    public static PlayerController Instance { get; private set; }

    [SerializeField] private InputActionAsset _inputAsset;
    [SerializeField] private InputActionReference _movementAction;
    [SerializeField] private InputActionReference _interactionAction;

    private HUDManager _hudManager;

    private Object _object;

    public void Start() {
        _hudManager = HUDManager.Instance;
    }

    protected override void Awake() {
        base.Awake();
        if (_inputAsset == null || _interactionAction == null) return;

        _interactionAction.action.performed += ctx => _interactionBehaviour.Interact();


        if (Instance != null) {
            Debug.LogError("What? 2 players crazy!!!");
        }

        Instance = this;
    }


    private void OnEnable() {
        if (_inputAsset == null || _interactionAction == null) return;
        _inputAsset.Enable();
    }

    private void OnDisable() {
        if (_inputAsset == null) return;
        _inputAsset.Disable();
    }

    private void Update() {
        if (_hudManager == null) {
            Debug.LogError("No HUDManager found");
            return;
        }
        if (!_hudManager.isUiOpen) {
            HandleMovementInput();
            HandleInteraction();
        }
    }

    private void HandleInteraction() {
        if (_movementBehaviour == null)
            return;
        if (_interactionBehaviour == null)
            return;

        _interactionBehaviour.HandleInteraction();
    }

    void HandleMovementInput() {
        if (_movementBehaviour == null ||
            _movementAction == null)
            return;
        Vector2 movementInput = _movementAction.action.ReadValue<Vector2>();
        Vector3 desiredDirection = new Vector3(movementInput.x, 0, movementInput.y);

        _movementBehaviour.desiredMovementDirection = desiredDirection;
        _movementBehaviour.desiredLookDirection = desiredDirection;
    }
}