using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float lookSpeed;

    Transform target;
    NavMeshAgent agent;

    Vector3 direction = Vector3.zero;
    Quaternion lookRotation = new Quaternion();


    PhotonView photonView;

    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
        photonView = GetComponent<PhotonView>();
    }

    // Start is called before the first frame update
    void Start()
    {
        if (!photonView.IsMine) this.enabled = false;
    }

    private void OnDestroy()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (target != null)
        {
            agent.SetDestination(target.position);
            FaceTarget();
        }
    }

    public void ToggleAgentMoving(bool busy)
    {
        agent.isStopped = busy;
    }

    public void MoveToPoint(Vector3 point)
    {
        agent.SetDestination(point);
    }

    public void FollowTarget(Interactable newTarget)
    {
        agent.stoppingDistance = newTarget.radius * 0.8f;
        agent.updateRotation = false;

        target = newTarget.interactionTransform;
        FaceTarget();
    }

    public void StopFollowingTarget()
    {
        agent.stoppingDistance = 0f;
        agent.updateRotation = true;

        target = null;
    }

    public void FaceAttack(int index)
    {
        if (target != null)
            FaceTarget();
    }

    public void FaceTarget()
    {
        if (target == null) return;

        direction = (target.position - transform.position).normalized;
        direction.y = 0f;
        lookRotation = Quaternion.LookRotation(direction);
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * lookSpeed);
    }

    public void InstantFaceTarget()
    {
        if (target != null)
        {
            direction = (target.position - transform.position).normalized;
            direction.y = 0f;
            lookRotation = Quaternion.LookRotation(direction);
            transform.rotation = lookRotation;
        }
    }

    public void InstantFaceCast(Vector3 lookat)
    {
        transform.forward = lookat;
    }

    public void StopLocomotion(int index)
    {
        StopFollowingTarget();
        agent.SetDestination(this.transform.position);
    }
}
