using System;
using System.Collections.Generic;
using UnityEngine;

public class UnitManager : MonoBehaviour {
    public static UnitManager Instance { get; private set; }
    private List<Unit> UnitList { get; } = new();
    private List<Unit> FriendlyUnitList{ get; } = new();
    public List<Unit> EnemyUnitList { get; } = new();
    
    private void Awake() {
        if (Instance is not null) {
            Debug.LogError($"There is more than one UnitManager! {transform} - {Instance}");
            Destroy(gameObject);
            return;
        }
        Instance = this;
    }
    private void Start() {
        Unit.OnAnyUnitSpawned += Unit_OnAnyUnitSpawned;
        Unit.OnAnyUnitDead += Unit_OnAnyUnitDead;
    }

    private void Unit_OnAnyUnitSpawned(object sender, EventArgs e) {
        if (sender is not Unit unit) return;
        UnitList.Add(unit);
        if (unit.IsEnemy) EnemyUnitList.Add(unit);
        else FriendlyUnitList.Add(unit);
    }

    private void Unit_OnAnyUnitDead(object sender, EventArgs e) {
        if (sender is not Unit unit) return;
        UnitList.Remove(unit);
        if (unit.IsEnemy) EnemyUnitList.Remove(unit);
        else FriendlyUnitList.Remove(unit);
    }
}
