using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

[RequireComponent(typeof(NPC))]
class EscapingWizard : MonoBehaviour
{
    private HardLight2D wizardlight;
    private HardLight2D[] lights;
    private Rigidbody2D myRigidbody;
    public Animator anim;

    private Vector2 movement;
    public bool shouldRotate;
    public Vector3 dir;

    [Header("Following Logic")]
    public Transform targetPosition;

    public AStarPathfindingAgent agent;

    public bool isDuringEscaping = false; // var is setted by trigger range 
    

    public float escapingRadius = 6f;  // radious where Wizard start escaping if player is in 


    public void Awake()
    {
        agent = GetComponent<AStarPathfindingAgent>();
    }

    private void Start()
    {
    }

    private void Update()
    {
        if(targetPosition == null)
        {
            targetPosition = GameObject.FindGameObjectWithTag("SceneTransition")?.transform;
        }


        //StopAllCoroutines();

        if (IsInEscapingRadious())
        {
            gameObject.GetComponent<NPC>().State = NPCStateEnum.Walking;

            // Animation config
            dir = targetPosition.position - transform.position;
            float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            dir.Normalize();
            movement = dir;
            anim.SetBool("isRunning", movement != Vector2.zero);

            if (shouldRotate)
            {
                anim.SetFloat("Xinfo", dir.x);
                anim.SetFloat("Yinfo", dir.y);
            }


            agent.point = targetPosition.position;
            StopAllCoroutines();
            //Debug.Log("FOLLOWINGPATH STARTED");
            agent.FindPoint();
            //agent.FindPath();
            StartCoroutine(agent.FollowPath());

        } else
        {
            StopAllCoroutines();

            gameObject.GetComponent<NPC>().State = NPCStateEnum.Pending;

            anim.SetBool("isRunning", false);
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.magenta;
        Gizmos.DrawWireSphere(transform.position,escapingRadius);
    }

    
    public bool IsInEscapingRadious()
    {
        if (Vector2.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, transform.position) >= escapingRadius)
            return false;

        return true;
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.collider.tag == "SceneTransition")
        {
            DungeonManager.SetTeleported();

            Destroy(gameObject);
        }
    }
}