using UnityEngine;

public class Vision : MonoBehaviour 
{
    public float Radius;

    private static int DarknessMask;
    private static int BlocksVisionMask;
    private static float BlockLeniency = 0.6f;

    private Collider2D[] seenList = new Collider2D[200];

    void Update()
    {
        ClearDarknessAround(transform, Radius, seenList);
    }

    public static void ClearDarknessAround(Transform observer, float radius, Collider2D[] seenList)
    {
        DarknessMask = LayerMask.GetMask("Darkness");
        BlocksVisionMask = LayerMask.GetMask("Terrain");

        int seen = Physics2D.OverlapCircleNonAlloc(observer.position, radius, seenList, DarknessMask);
        for(int i=0; i<seen; i++)
        {
            if(HasLineOfSight(observer, seenList[i]))
                Clear(seenList[i]);
        }
	}

    private static bool HasLineOfSight(Transform observer, Collider2D dark)
    {
        Vector2 delta = (dark.transform.position - observer.position);
        RaycastHit2D hit = Physics2D.Raycast(observer.position, delta, delta.magnitude - BlockLeniency, BlocksVisionMask);

        //if(hit.collider != null)
        //{
        //    Debug.DrawLine(observer.position, observer.position + (Vector3)delta.normalized * (delta.magnitude - BlockLeniency), Color.red);
        //}

        return hit.collider == null;
    }

    private static void Clear(Collider2D c)
    {
        Darkness dark = c.GetComponent<Darkness>();
        dark.Clear();
    }
}
