using Unity.MLAgents;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private static GameManager instance;
    public static GameManager Instance { get { return instance; } }

    private static SimpleMultiAgentGroup DefendersTeam = new SimpleMultiAgentGroup();
    private static SimpleMultiAgentGroup AttackersTeam = new SimpleMultiAgentGroup();

    private void Awake()
    {
        if (Instance == null)
            instance = this;
        else if (Instance == this)
            Destroy(gameObject);
    }

    private void Start()
    {
        GlobalEventManager.onCaptureFlag += flagCaptured;
        GlobalEventManager.onTimeLeft += timeOut;

        var agents = GameObject.FindObjectsOfType<Agent>();
        foreach (var item in agents)
        {
            var agent = item as NPC;
            if (agent.GetCharacter.Team == Team.Attackers)
                AttackersTeam.RegisterAgent(agent);
            else
                DefendersTeam.RegisterAgent(agent);
        }
    }

    public static bool IsCloserToEnemyThanToNextNavPoint(NavPoint navPoint, Vector3 currentTransform, Team team)
    {
        SimpleMultiAgentGroup agentGroup;
        if (team == Team.Attackers)
            agentGroup = AttackersTeam;
        else
            agentGroup = DefendersTeam;

        var distToNavPoint = (currentTransform - navPoint.position).magnitude;
        foreach (var agent in agentGroup.GetRegisteredAgents())
            if (distToNavPoint > (currentTransform - agent.transform.position).magnitude)
                return true;
        return false;
    }

    public static bool IsCloserToFlagFromNextNavPoint(NavPoint navPoint, Vector3 currentTransform)
        => navPoint.FlagDistance < (currentTransform - GameObject.FindGameObjectWithTag("Flag").transform.position).magnitude;

    private void flagCaptured(Team team)
    {
        switch(team)
        {
            case Team.Attackers:
                Debug.Log("Attackers Win");
                break;
            case Team.Defenders:
                Debug.Log("Defenders Win");
                break;
            default:
                Debug.LogError("Unexpected Team");
                break;
        }
    }

    private void timeOut()
    {
        Debug.Log("Time is out");
    }

    private void OnDestroy()
    {
        GlobalEventManager.onCaptureFlag -= flagCaptured;
        GlobalEventManager.onTimeLeft -= timeOut;
    }
}
