using UnityEngine;
using System.Linq;

public class AIUtil : MonoBehaviour 
{
    private static int losMask = LayerMask.GetMask("Terrain");


    public static Transform NearestVisibleHuman(Vector3 pos, float maxDist=-1)
    {
        GameObject[] gos;
        gos = GameObject.FindGameObjectsWithTag("Human");

        foreach(GameObject human in gos.OrderBy(h => (h.transform.position - pos).magnitude))
        {
            bool inRange = (maxDist == -1 || maxDist >= (human.transform.position - pos).magnitude);
            if (!inRange)
                continue;

            if (HasLoS(pos, human.transform.position, 0.5f))
                return human.transform;
        }

        return null;
    }

    public static bool HasLoS(Vector2 from, Vector2 to, float leniency = 0f)
    {
        Vector2 delta = (to - from);
        RaycastHit2D hit = Physics2D.Raycast(from, delta, delta.magnitude - leniency, losMask);

        if (hit.collider != null)
            Debug.DrawLine(from, hit.point, Color.cyan);

        return hit.collider == null;
    }

    
}
