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

using UnityEngine;
using Random = UnityEngine.Random;

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

    private List<GameObject> pickups;
    [SerializeField] private GameObject healthPrefab;
    [SerializeField] private GameObject armourPrefab;
    [SerializeField] private GameObject ammoPrefab;

    [SerializeField] private List<NavPoint> spawnPoints;

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

    private void Start()
    {
        pickups = new List<GameObject>();
        var amount = SettingsReader.Instance.GetSettings.PickupsAmount;
        for (int i = 0; i < amount; i++)
            pickups.Add(GameObject.Instantiate(healthPrefab, spawnPoints[Random.Range(0, spawnPoints.Count)].transform.position, Quaternion.identity));
        for (int i = 0; i < amount; i++)
            pickups.Add(GameObject.Instantiate(armourPrefab, spawnPoints[Random.Range(0, spawnPoints.Count)].transform.position, Quaternion.identity));
        for (int i = 0; i < amount; i++)
        {
            pickups.Add(GameObject.Instantiate(ammoPrefab, spawnPoints[Random.Range(0, spawnPoints.Count)].transform.position, Quaternion.identity));
        }
        foreach (var gameobj in pickups)
            gameobj.SetActive(true);

        StartCoroutine(SpawnNewPickUps());
    }

    private IEnumerator SpawnNewPickUps()
    {
        while (true)
        {
            GameObject item;
            if (IsDisableCheck(out item))
            {
                yield return new WaitForSeconds(3);
                if (item != null)
                {
                    item.transform.position = spawnPoints[Random.Range(0, spawnPoints.Count)].Position;
                    item.SetActive(true);
                }
            }
            yield return new WaitForSeconds(2);
        }
    }

    private bool IsDisableCheck(out GameObject gameobj)
    {
        foreach (var pick in pickups)
        {
            if (!pick.activeInHierarchy)
            {
                gameobj = pick;
                return true;
            }
        }
        gameobj = null;
        return false;
    }
}
