namespace Scripts.IA
{
    using UnityEngine;
    using Scripts.Waypoints;
    using Mapbox.Utils;
    using Mapbox.Unity.Map;

    public class Runners : MonoBehaviour
    {
        public float speed = 10f;
        public float motivation;
        private AbstractMap _map;

        private Vector3 target;
        private int waypointIndex = 0;

        void Start()
        {
            motivation = 50f;
            _map = GameObject.Find("Map").GetComponent<AbstractMap>();

            Debug.Log("JE SUIS CREE !");
            target = _map.GeoToWorldPosition(WaypointsFactory.getInstance().getWp()[0]);

            float vitesse = (float.Parse(RunnersFactory.getInstance().getRandom().Next(75, 125).ToString()) / 100f) * 10f;
            speed = vitesse;
        }

        private void Update()
        {
            Vector3 dir = target - transform.position;
            transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);

            if (Vector3.Distance(transform.position, target) <= 0.3f) //Marge d'erreur
            {
                GetNextWaypoint();
            }

            if (Ui.difficulty < MotivScale.diff_min)
            {//0.01 0.010 | 1 10
                motivation = motivation - ((float.Parse(RunnersFactory.getInstance().getRandom().Next(1, 10).ToString()) / 500f) * (MotivScale.diff_min - Ui.difficulty));
            }
            else if (Ui.difficulty > MotivScale.diff_max)
            {
                motivation = motivation - ((float.Parse(RunnersFactory.getInstance().getRandom().Next(1, 10).ToString()) / 500f) * (Ui.difficulty - MotivScale.diff_max));
            }
            else
            {
                motivation = motivation + (float.Parse(RunnersFactory.getInstance().getRandom().Next(1, 10).ToString()) / 500f);
            }

            if (motivation <= 0) Destroy(gameObject);
        }

        private void GetNextWaypoint()
        {
            Debug.Log(target.ToString());
            if (waypointIndex >= WaypointsFactory.getInstance().getWp().Count - 1)
            {
                Destroy(gameObject);
                return;
            }

            waypointIndex++;
            target = _map.GeoToWorldPosition(WaypointsFactory.getInstance().getWp()[waypointIndex]);
        }
    }
}