using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Allegiance;

public class Spawner : MonoBehaviour
{
    [SerializeField] private List<GameObject> enemyPrefabs;
    [SerializeField] private float spawnCooldown = 5f;
    [SerializeField] private float minSpawnCD = 3f;
    [SerializeField] private float maxSpawnCD = 6f;
    // [SerializeField] private int maxSpawns = 5;

    private Ticker cooldown;
    private bool onCooldown;
    private List<GameObject> spawns;

    void Awake() {
        EnemyManager.I.spawnEnemies += Spawn;
        spawnCooldown = Random.Range(minSpawnCD, maxSpawnCD);
        cooldown = new Ticker(spawnCooldown);
        onCooldown = false;
        // spawns = new List<GameObject>();

        cooldown.onTick.AddListener(OffCooldown);
    }

    void Update() {
        // foreach(GameObject spawn in spawns) {
        //     if(spawn == null)
        //         spawns.Remove(spawn);
        // }
        if(onCooldown) {
            cooldown.Tick(Time.deltaTime);
        }
    }

    private void OffCooldown() {
        onCooldown = false;
    }

    public void Spawn(int randomValue) {
        if(!onCooldown) {
            onCooldown = true;
            if(PlayerManager.I.unit == null) {
                GameObject enemy = Pool.Get(enemyPrefabs[randomValue % enemyPrefabs.Count], this.transform.position);
                BasicWeapon weapon = enemy.GetComponent<BasicWeapon>();
                weapon.owner = Ownership.PLAYER;
                PlayerManager.I.unit = weapon.gameObject.GetComponent<UnitController>();
                weapon.enabled = true;
            }
            else {
                // if(spawns.Count < maxSpawns) {
                    GameObject enemy = Pool.Get(enemyPrefabs[randomValue % enemyPrefabs.Count], this.transform.position);
                    BasicWeapon weapon = enemy.GetComponent<BasicWeapon>();
                    // spawns.Add(enemy);
                    weapon.owner = Ownership.ENEMY;
                    weapon.enabled = true;
                // }
            }
        }
    }

    void OnDestroy() {
        if(EnemyManager.HasInstance) {
            EnemyManager.I.spawnEnemies -= Spawn;
        }
    }
}
