using System.Collections.Generic;
using UnityEngine;

public class GameManager : Singleton<GameManager>
{
    [SerializeField]
    PlayerController playerPrefab;
    [SerializeField]
    Home homePrefab;
    [SerializeField]
    Transform[] playerSpawnPosition;
    [SerializeField]
    Transform[] homeSpawnPosition;
    [SerializeField]
    Color[] playerColors = new Color[4] { Color.red, Color.blue, Color.cyan, Color.green };

    List<PlayerController> playerList = new List<PlayerController>();

    Home[] homes;

    public bool IsGameOver { get; private set; }

    protected override void OnAwake()
    {
       // UIManager.Instance.Show<UIGame>();
        SpawnPlayers(GameData.ActivePlayers);

        SpawnHomes();
    }

    void SpawnHomes()
    {
        homes = new Home[homeSpawnPosition.Length];

        for (int i = 0; i < homes.Length; i++)
        {
            Home home = Instantiate(homePrefab,
                new Vector3(homeSpawnPosition[i].transform.position.x,
                            homeSpawnPosition[i].transform.position.y + 0.5f,   
                        homeSpawnPosition[i].transform.position.z),
                                    homePrefab.transform.rotation);

            homes[i] = home;
        }
    }

    void SpawnPlayers(int playerCount)
    {
        for (int i = 0; i < playerCount; i++)
        {
            PlayerController player = Instantiate(playerPrefab, 
                                                  playerSpawnPosition[i].transform.position, 
                                                  playerPrefab.transform.rotation);

            player.InitPlayer(i, playerColors[i]);
            player.gameObject.name = "Player";
            playerList.Add(player);
        }
    }

    public void GameOver(PlayerController winner)
    {
        for (int i = 0; i < playerList.Count; i++)
        {
            if(playerList[i] != winner)
            {
                Destroy(playerList[i].gameObject);
            }
        }

        IsGameOver = true;
    }

    public void AreAllHomesOwnedByOnePlayer(PlayerController player)
    {
        for (int i = 0; i < homes.Length; i++)
        {
            if(homes[i].OwningPlayer != player)
            {
                return;
            }
        }
        GameOver(player);
    }


}
