using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using UnityEngine;
using UnityEngine.AI;

public class EnemyAi : MonoBehaviour
{
    public NavMeshAgent agent;
    public Transform player;
    public LayerMask groundMask;
    public LayerMask playerMask;
    public int health = 100;

    /// <summary>
    /// patrol variables
    /// </summary>
    public Vector3 WalkPoint;
    private bool walkPointSet = false;
    public float walkRange;
    public float sightRange;
    public float attackRange;
    private bool playerInSightRange;
    private bool playerInAttackRange;
    public GameObject gun;



    void Update()
    {

        //Check for sight and attack range
        playerInSightRange = Physics.CheckSphere(transform.position, sightRange, playerMask);
        playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, playerMask);

        if (!playerInSightRange && !playerInAttackRange)
            Patrol();
        if (playerInSightRange && !playerInAttackRange)
            Chase();
        if (playerInAttackRange && playerInSightRange)
            Attack();
        if (health <= 0)
        {
            Destroy(gameObject);
        }
        if(player == null)
        {
            player=GameObject.Find("PlayerCapsule").transform;
        }
    }

    private void Patrol()
    {
        Debug.Log("Patroling");
        if (!walkPointSet)
        {
            SeachWalkPoint();
        }
        else
        {
            agent.SetDestination(WalkPoint);
        }
        ;
        Vector3 distaceToWalk = transform.position - WalkPoint;
        if (distaceToWalk.magnitude < 1f)
        {
            Invoke("changePoint",4f);
        }
    }
    public void changePoint()
    {
                    walkPointSet = false;

    }
    private void SeachWalkPoint()
    {
        float randomZ = Random.Range(-walkRange, walkRange);
        float randomX = Random.Range(-walkRange, walkRange);

        WalkPoint = new Vector3(
            transform.position.x + randomX,
            transform.position.y,
            transform.position.z + randomZ
        );

        if (Physics.Raycast(WalkPoint, -transform.up, 2f, groundMask))
        {
            walkPointSet = true;
        }
    }

    private void Chase()
    {
        Debug.Log("chasing");

        agent.SetDestination(player.position);
    }

    private void Attack()
    {
        Debug.Log("Attacking");

        agent.SetDestination(transform.position);

        transform.LookAt(player);

        gun.GetComponent<enemyGun>().Shoot();
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, attackRange);
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, sightRange);
    }
}
