using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
using Unheimlich.Core;
using Unheimlich.Gameplay.Items;
using InputManager = Unheimlich.Managers.PlayerInputManager;
namespace Unheimlich.Interactions.Core
{
///
/// Handles player item inspection mode.
/// When inspecting, disables player movement and allows item rotation using look input.
///
public class PlayerInspectionHandler : Singleton
{
[Header("Components")]
[SerializeField] private Transform _inspectionHoldPoint;
[Header("State")]
public bool IsInspecting { get; private set; } = false;
private InspectableItem _currentInspectedItem;
private Coroutine _interactionListener;
private bool _isUsingGamepad = false;
public void ToggleInspection(InspectableItem item)
{
if (!IsInspecting)
{
StartInspection(item);
}
else
{
if (_interactionListener != null)
StopInspection();
}
}
private void StartInspection(InspectableItem item)
{
IsInspecting = true;
_currentInspectedItem = item;
InputManager.ToggleInput(false);
item.PrepareForInspection(_inspectionHoldPoint);
if (_interactionListener == null)
_interactionListener = StartCoroutine(ListenForInteraction());
}
private void StopInspection()
{
if (_interactionListener != null)
{
StopCoroutine(_interactionListener);
_interactionListener = null;
}
StopInspectionInternal();
}
private void StopInspectionInternal()
{
if (_currentInspectedItem != null)
{
_currentInspectedItem.Release();
_currentInspectedItem = null;
StartCoroutine(DelayedToggleInput(true));
}
IsInspecting = false;
}
private IEnumerator DelayedToggleInput(bool enable)
{
yield return new WaitForEndOfFrame();
InputManager.ToggleInput(enable);
}
private IEnumerator ListenForInteraction()
{
yield return null;
while (IsInspecting)
{
if (InputManager.Instance.InteractAction.action.WasPressedThisFrame())
{
StopInspectionInternal();
yield break;
}
yield return null;
}
_interactionListener = null;
}
private void Update()
{
if (IsInspecting && _currentInspectedItem != null)
{
HandleObjectRotation();
}
}
private void HandleObjectRotation()
{
if (InputManager.Instance == null) return;
Vector2 lookInput = InputManager.Instance.LookInput;
if (lookInput != Vector2.zero)
{
if (Gamepad.current != null && Gamepad.current.rightStick.ReadValue().magnitude > 0.01f)
_isUsingGamepad = true;
else if (Mouse.current != null && Mouse.current.delta.ReadValue().magnitude > 0.01f)
_isUsingGamepad = false;
float deltaMultiplier = _isUsingGamepad ? Time.deltaTime : 0.005f;
float rotX = lookInput.y * _currentInspectedItem.RotationSpeed * deltaMultiplier;
float rotY = lookInput.x * _currentInspectedItem.RotationSpeed * deltaMultiplier;
_currentInspectedItem.transform.Rotate(transform.up, -rotY, Space.World);
_currentInspectedItem.transform.Rotate(transform.right, rotX, Space.World);
}
}
}
}