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

public class BuildingManager : MonoBehaviour
{
    private List<Building> _buildings;

    private float _globalLife = 0.0f;

    private void Start()
    {
        _buildings = new List<Building>(GetComponentsInChildren<Building>());
        foreach (Building building in _buildings)
        {
            building.Init(this);
            building.OnBreaked += OnBreaked;
            building.OnLifeLost += OnLifeLost;
            _globalLife += building.Life;
        }
        GameSceneManager.Instance.UiManager.GamePanel.DisplayLifeCount(_globalLife);
    }

    private void OnBreaked(Building destroyedBuilding)
    {
        foreach (Building building in _buildings)
        {
            if (building.IsAlive)
            {
                return;
            }
        }
        GameManager.Instance.GameOver();
    }

    private void OnLifeLost(float lifeLost, float remiaingLife)
    {
        _globalLife -= lifeLost;
        GameSceneManager.Instance.UiManager.GamePanel.DisplayLifeCount(_globalLife);
    }

    public Building GetRandomBuild()
    {
        _buildings.Sort(Order);
        return _buildings[0];
    }

    private static int Order(Building x, Building y)
    {
        if (x.IsAlive == false)
            return 1;
        if (y.IsAlive == false)
            return -1;

        if (x.AttackerCount > y.AttackerCount)
        {
            return 1;
        }
        else if (y.AttackerCount > x.AttackerCount)
        {
            return -1;
        }
        else
        {
            return Random.Range(-1, 1);
        }
    }
}
