using System.Collections;
using System.Collections.Generic;
using Game.Plugins.App.Game.RVO;
using Game.Plugins.App.Game.RVO2;
using Game.Plugins.App.Sync;
using HPJ.Presentation;
using Plugins.JNGame.Sync.Frame.game.Time;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;

public class PlayerController : JNGSyncFrameDefault
{
    
    // Vector3 _target;
    private NavMeshPath _path;
    private Queue<Vector3> _queue = new();
    //下一个目标点
    private Vector3 nextPos;
    
    //多久没有移动到下一个目标
    private int timeNextPos;
    
    public override void OnSyncLoad()
    {
        this.GetComponent<NavMeshAgent>().updatePosition = false;
        this.GetComponent<NavMeshAgent>().updateRotation = false;
        // this.GetComponent<NavMeshAgent>().Stop();
    }

    public void SetPath(Vector3 target)
    {
        _path = new NavMeshPath();
        _queue.Clear();
        NavMesh.CalculatePath(this.transform.position,target,NavMesh.AllAreas,_path);
        if (_path.status == NavMeshPathStatus.PathComplete)
        {
            Vector3 lastPos = this.transform.position;
            for (var i = 0; i < _path.corners.Length; i++)
            {
                while (Vector3.Distance(lastPos,_path.corners[i]) >= 1)
                {
                    Vector3 directionToTarget = (_path.corners[i] - lastPos).normalized;
                    float distanceToMove = Mathf.Min(1, Vector3.Distance(lastPos, _path.corners[i]));
                    lastPos = lastPos + (directionToTarget * distanceToMove);  
                    _queue.Enqueue(lastPos);
                }
                _queue.Enqueue(_path.corners[i]);
            }
            _queue.TryDequeue(out nextPos);
            this.GetComponent<JNGRVO2Agent>().SetTarget(nextPos);
        }
    }

    public override void OnSyncUpdate(int dt, JNFrameInfo frame, Object input)
    {
        if(_queue.Count > 0 && (timeNextPos += dt) > 3000)
            this.SetPath(new Vector3(10, 0, 10));
        // // this.SetPath(new Vector3(10, 0, 10));
        while(_queue.Count > 0 && Vector2.Distance(new Vector2(nextPos.x,nextPos.z),new Vector2(this.transform.position.x,this.transform.position.z)) <= 1.5)
        {
            timeNextPos = 0;
            if (_queue.TryDequeue(out nextPos))
            {
                this.GetComponent<JNGRVO2Agent>().SetTarget(nextPos);
            }
            // SetPath(new Vector3(10, 0, 10));
        }

        if (frame.Index == 20)
        {
            this.SetPath(new Vector3(10, 0, 10));
        }
    }
}
