using System.Collections;
using Pathfinding;
using UnityEngine;

[RequireComponent (typeof (Rigidbody2D))]
[RequireComponent(typeof(Seeker))]

public class PeopleAI : MonoBehaviour {
    
    // What to chase?
    public Transform target1;
    public Transform target2;

    // How many times each second we will update our path
    public float updateRate = 2f;

    // Catching
    private Seeker seeker;
    private Rigidbody2D rb;

    // The calculated path
    public Path path;

    // The AI's speed per second
    public float speed = 300f;
    public ForceMode2D fMode;

    [HideInInspector]
    public bool pathIsEnded = false;

    Vector3 dir;

    // The max distance from the AI to a waypoint for it to continue to the next waypoint 
    public float nextWaypointDistance = 5;

    // The waypoint that wwe are currently heading towards
    private int currentWaypoint = 0;
   

    private void Start()
    {

        seeker = GetComponent<Seeker>();
        rb = GetComponent<Rigidbody2D>();
        

        if (target1 == null || target2 == null)
        {
            Debug.LogError("No Player Found PANIC!");
            return;
        }
        // start a new path to a targtet position and the return the result to the OnPathComplete method
        seeker.StartPath(transform.position, target1.position, OnPathComplete);

        seeker.StartPath(transform.position, target2.position, OnPathComplete);

        StartCoroutine(UpdatePath ());
    }

    IEnumerator UpdatePath ()
    {
        if (target1 == null || target2 == null)
        {
           yield return false;
        }
        seeker.StartPath(transform.position, target1.position, OnPathComplete);
        seeker.StartPath(transform.position, target2.position, OnPathComplete);


        yield return new WaitForSeconds( 1f/updateRate);
        StartCoroutine(UpdatePath());
    }

    public void OnPathComplete (Path p)
    {
        Debug.Log("We got a path, did it have an error?" + p.error);
        if (!p.error)
        {
            path = p;
            currentWaypoint = 6;


        }
    }

  

    public void FixedUpdate()
    {
        if (target1 == null || target2 == null)
        {
            return;
        }

        if (path == null)
            return;

        if (currentWaypoint >= path.vectorPath.Count)
        { 
            if (pathIsEnded)
                return;

                Debug.Log("End of Path Reached!");
                pathIsEnded = true;
                return;
        }
            pathIsEnded = false;

            //direction to the next waypoint
            dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
            dir *= speed * Time.fixedDeltaTime;

        //Move the AI away from players 
        rb.AddForce(-dir, fMode);

        float dist = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
            

        if (dist > nextWaypointDistance)
        {
            currentWaypoint++;
            return;
        }
    }



    public void OnCollisionEnter2D(Collision2D collisionInfo)
        {
        if (collisionInfo.collider.name == target1.name)
            {
                rb.AddForce(dir, fMode);
            }
        else if (collisionInfo.collider.name == target2.name)
            {
                rb.AddForce(dir, fMode);
            }
        else
        {
            rb.AddForce(-dir, fMode);
        }

    }
       









}

