using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AI;

public class EnemyRoamingState : EnemyBaseState
{
    private path currentPath = new();
    private int pointIndex = 0;
    private bool returning;
    public override void EnterState(EnemyStateManager manager)
    {
        currentPath = manager.pathList[Random.Range(0, manager.pathList.Length)];
        manager.agent.SetDestination(currentPath.points[pointIndex].position);
    }

    public override void UpdateState(EnemyStateManager manager)
    {
        if(manager.agent.remainingDistance < manager.newPointThreshold){
            if(!returning){
                if(pointIndex == currentPath.points.Length-1){
                    returning = true;
                    manager.agent.SetDestination(currentPath.points[0].position);
                    return;
                }
                pointIndex++;
                manager.agent.SetDestination(currentPath.points[pointIndex].position);
            }
            else{
                returning = false;
                pointIndex = 0;
                currentPath = manager.pathList[Random.Range(0, manager.pathList.Length)];
                manager.agent.SetDestination(currentPath.points[pointIndex].position);
            }
        }
        SearchForPlayer(manager);
    }

    private void SearchForPlayer(EnemyStateManager manager){
        float distance = Vector3.Distance(manager.transform.position, manager.player.position);
        if(distance < manager.playerBehindDetectionThreshold){
            if(!CheckPlayerVisibility(manager))
                return;

            manager.SwitchState(manager.followState);
        }
        else if(distance < manager.playerInFrontDetectionThreshold){
            if(!CheckPlayerVisibility(manager))
                return;
            Vector3 playerDirection = manager.player.transform.position-manager.transform.position;
            if(Vector3.Dot(manager.transform.forward, playerDirection) > manager.dotProductThreshold){
                manager.SwitchState(manager.followState);
            }
        }
    }

    private bool CheckPlayerVisibility(EnemyStateManager manager){
        if(Physics.Linecast(manager.head.position, manager.playerHead.position, out var hit)){
            if(hit.transform.CompareTag("Player"))
                return true;
            else
                return false;
        }
        else{
            return false;
        }
    }
}
