using System.Collections;
using System.Collections.Generic;
using Com.LuisPedroFonseca.ProCamera2D;
using UnityEngine;

public class RespawnManager : MonoBehaviour
{
    public GameObject[] spawnPositions;

    public GameObject CharacterPrefab;

    public UnityEngine.UI.Image[] playerUI;

    public ProCamera2D[] camera;

    void Start()
    {
        // Always add one player
        if (GameState.Instance.EnabledPlayers.Count == 0)
        {            
            GameState.Instance.SetPlayerState(0, true);
        }
        
        if (GameState.Instance.EnabledPlayers.Count == 1)
        {
            camera[0].GetComponent<Camera>().rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
            camera[1].GetComponent<Camera>().enabled = false;
            camera[2].GetComponent<Camera>().enabled = false;
            camera[3].GetComponent<Camera>().enabled = false;
        }
        else if (GameState.Instance.EnabledPlayers.Count == 2)
        {
            camera[0].GetComponent<Camera>().rect = new Rect(0.0f, 0.5f, 0.5f, 1f);
            camera[1].GetComponent<Camera>().rect = new Rect(0.5f, 0.5f, 0.5f, 1f);
            camera[2].GetComponent<Camera>().enabled = false;
            camera[3].GetComponent<Camera>().enabled = false;
        }
        else if (GameState.Instance.EnabledPlayers.Count == 3)
        {
            camera[0].GetComponent<Camera>().rect = new Rect(0.0f, 0.5f, 0.5f, 0.5f);
            camera[1].GetComponent<Camera>().rect = new Rect(0.5f, 0.5f, 0.5f, 0.5f);
            camera[2].GetComponent<Camera>().rect = new Rect(0.0f, 0.0f, 0.5f, 0.5f);
            camera[3].GetComponent<Camera>().enabled = false;
        }
        else if (GameState.Instance.EnabledPlayers.Count == 4)
        {
            camera[0].GetComponent<Camera>().rect = new Rect(0.0f, 0.5f, 0.5f, 0.5f);
            camera[1].GetComponent<Camera>().rect = new Rect(0.5f, 0.5f, 0.5f, 0.5f);
            camera[2].GetComponent<Camera>().rect = new Rect(0.0f, 0.0f, 0.5f, 0.5f);
            camera[3].GetComponent<Camera>().rect = new Rect(0.5f, 0.0f, 0.5f, 0.5f);
        }

        for (var i = 0; i < GameState.Instance.EnabledPlayers.Count; i++)
        {
            var player = GameState.Instance.EnabledPlayers[i];

            int spawnIndex = Random.Range(0, spawnPositions.Length);
            Vector3 startPos = spawnPositions[spawnIndex].transform.position;

            GameObject character = Instantiate(CharacterPrefab, startPos, Quaternion.identity);

            playerUI[player.PlayerId].gameObject.SetActive(true);

            camera[player.PlayerId].AddCameraTarget(character.transform);
            
            character.GetComponent<PlayerController>().Init(player.PlayerId);
            character.GetComponent<PlayerColorRepresentation>().SetColor(player, playerUI[player.PlayerId]);
        }
    }
}
