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

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

    [SerializeField] private List<NavPoint> spawnPointsForDefendersTeam;
    [SerializeField] private List<NavPoint> spawnPointsForAttackersTeam;
    [SerializeField] private GameObject AIPrefab;
    [SerializeField] private GameObject PlayerPrefab;

    private List<GameObject> Players;

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

    private void Start()
    {
        var attcNum = SettingsReader.Instance.GetSettings.numOfAttackers;
        var defNum = SettingsReader.Instance.GetSettings.numOfDefenders;
        var humanDef = SettingsReader.Instance.GetSettings.hasHumanDefender == true ? 1 : 0;
        var humanAtc = SettingsReader.Instance.GetSettings.hasHumanAttacker == true ? 1 : 0;

        if (humanAtc == 1 && humanDef == 1)
            throw new System.ArgumentException("Can be only one human player");

        for (int i = 0; i < attcNum - humanAtc; i++)
            InstanciateEntity(Team.Attackers, TypeAI.D0DiskAI,
                spawnPointsForAttackersTeam[Random.Range(0, spawnPointsForAttackersTeam.Count)]);
        for (int i = 0; i < defNum - humanDef; i++)
            InstanciateEntity(Team.Defenders, TypeAI.D0DiskAI,
                spawnPointsForDefendersTeam[Random.Range(0, spawnPointsForDefendersTeam.Count)]);
        if (humanAtc == 1)
            InstanciateEntity(Team.Attackers, TypeAI.HumanAI,
                spawnPointsForAttackersTeam[Random.Range(0, spawnPointsForAttackersTeam.Count)]);
        if (humanDef == 1)
            InstanciateEntity(Team.Defenders, TypeAI.HumanAI,
                spawnPointsForDefendersTeam[Random.Range(0, spawnPointsForDefendersTeam.Count)]);
    }

    private void InstanciateEntity(Team team, TypeAI typeAi, NavPoint spawnPoint)
    {
        var gameobject = GameObject.Instantiate(
            typeAi == TypeAI.HumanAI ? PlayerPrefab : AIPrefab,
            spawnPoint.position,
            Quaternion.identity);
        
        var character = gameObject.GetComponent<ICharacter>();
        character.GetCharacter.Team = team;
    }
}