using System.Threading.Tasks;
using Game.Plugins.App.Sync;
using Game.Plugins.JNGame.Sync.Frame.AstarPath.RVO;
using UnityEngine;

namespace Game.Plugins.App.Game.RVO
{
    public class JNGRVOAgent : JNGSyncFrameDefault
    {
        
        private JNRVOSimulator Simulator => GetComponentInParent<JNGRVOManager>().Simulator;

        private JNIAgent _agent;

        public float maxSpeed = 5;
        public float radius = 0.5f;

        private Vector2 target;
        
        public override void OnSyncLoad()
        {
            base.OnSyncLoad();
            var position = this.transform.position;
            _agent = Simulator.AddAgent(new JNRVOAgent(
                new Vector2(position.x, position.z), 0
            ));
            SetTarget(position);
            _agent.Radius = radius;
        }
        
        //设置目标点
        public void SetTarget(Vector2 targetPoint)
        {
            this.target = targetPoint;
        }
        public void SetTarget(Vector3 targetPoint)
        {
            this.target = new Vector2(targetPoint.x,targetPoint.z);
        }

        public override void OnSyncUpdate(int dt, JNFrameInfo frame, Object input)
        {
            
            base.OnSyncUpdate(dt, frame, input);
            var pos = _agent.Position;
            var deltaPosition = Vector2.ClampMagnitude(_agent.CalculatedTargetPoint - pos,
                _agent.CalculatedSpeed * GetSync().Time.deltaTime);
            pos += deltaPosition;
            _agent.Position = pos;

            var dist = (target - pos).magnitude;
            _agent.SetTarget(target, Mathf.Min(dist, maxSpeed), maxSpeed * 1.1f);
            this.transform.position = new Vector3(_agent.Position.x, _agent.ElevationCoordinate, _agent.Position.y);
            
        }
    }
}