using UnityEngine;
using UnityEngine.Serialization;

public class MouseWorld : MonoBehaviour {
    private static MouseWorld instance;

    [FormerlySerializedAs("MousePlaneLayerMask")] [SerializeField]
    private LayerMask mousePlaneLayerMask;

    private void Awake() => instance = this;

    // public static Vector3 GetPosition() {
    //     Ray ray = Camera.main.ScreenPointToRay(InputManager.Instance.GetMouseScreenPosition());
    //     Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, instance.mousePlaneLayerMask);
    //     return raycastHit.point;
    // }

    public static Vector3 GetPositionOnlyHitVisible() {
        Ray ray = Camera.main.ScreenPointToRay(InputManager.Instance.GetMouseScreenPosition());
        RaycastHit[] raycastHitArray = Physics.RaycastAll(ray, float.MaxValue, instance.mousePlaneLayerMask);
        System.Array.Sort(raycastHitArray, (RaycastHit raycastHitA, RaycastHit raycastHitB) => Mathf.RoundToInt(raycastHitA.distance - raycastHitB.distance));
        foreach (RaycastHit raycastHit in raycastHitArray) {
            if (!raycastHit.transform.TryGetComponent(out Renderer renderer)) continue;
            if (renderer.enabled) return raycastHit.point;
        }

        return Vector3.zero;
    }
}