using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MapManager : MonoBehaviour
{
    private static MapManager _instance;
    public static MapManager Instance => _instance;
    [SerializeField] private List<NavPoint> _navPoints;
    public List<NavPoint> NavPoints { get => _navPoints; private set => _navPoints = value; }
    public Dictionary<int, NavPoint> IDToNavPoint {get; private set; }

    private void Awake()
    {
        if (_instance is null)
            _instance = this;
        else
        {
            Destroy(gameObject);
            Debug.LogError("Only 1 Instance");
        }
        
        // NavPoints = new List<NavPoint>();
        // var navPointSet = GameObject.Find("NavPoint Set");
        // var count = navPointSet.transform.childCount;
        // for (var i=0; i < count; i++)        
        //     NavPoints.Add(navPointSet.transform.GetChild(i)
        //         .gameObject.GetComponent<NavPoint>());

        var rootObjInScene = new List<GameObject>();
        var scene = SceneManager.GetActiveScene();
        scene.GetRootGameObjects(rootObjInScene);
        foreach (var t in rootObjInScene)
        {
            NavPoints = t.GetComponentsInChildren<NavPoint>(true).ToList();
        }
        NavPointSetToID();
    }
    

    private void NavPointSetToID()
    {
        IDToNavPoint = new Dictionary<int, NavPoint>();
        int i = 0;
        foreach (var navPoint in NavPoints)
        {
            IDToNavPoint.Add(i, navPoint);
            navPoint.PointId = i;
            i++;
        }
    }

    public static void AddDeathAttributeToPoints(int startPoint, int endPoint, 
        float allDistance, float remainingDistance)
    {
        var startNavPoint = _instance.IDToNavPoint[startPoint];
        var endNavPoint = _instance.IDToNavPoint[endPoint];
        float coef; 
        if (Mathf.Abs(allDistance) > float.Epsilon)
        {
            coef = remainingDistance / allDistance;
            startNavPoint.DeathAttr += 1 - coef;
            endNavPoint.DeathAttr += coef;
        }
        else
        {
            startNavPoint.DeathAttr += 1;
        }
    }
}
