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

public class PickupSpawner : MonoBehaviour
{
    [SerializeField]
    private float _chancePerSecond = 0.05f;

    [SerializeField]
    private bool _guaranteeOnInit = false;

    [SerializeField]
    private GameObject[] _weaponPickups;

    [SerializeField]
    private GameObject[] _ammoPickups;

    [SerializeField]
    private GameObject _pickupPrefab;

    private GameObject _activePickup;

    void Start()
    {
        if (_guaranteeOnInit)
        {
            Spawn();
        }
        StartCoroutine(SpawnRoutine());
    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator SpawnRoutine()
    {
        while (true)
        {
            yield return new WaitForSeconds(1f);
            if (_activePickup == null && Random.Range(0f, 1f) < _chancePerSecond)
            {
                Spawn();
            }
        }
    }

    void Spawn()
    {
        _activePickup = Instantiate(_pickupPrefab, transform);
        Pickup pickup = _activePickup.GetComponent<Pickup>();
        int total = _weaponPickups.Length + _ammoPickups.Length;
        int randomId = Random.Range(0, total);
        if (randomId >= _weaponPickups.Length)
        {
            randomId -= _weaponPickups.Length;
            pickup.pickupType = PickupType.Ammo;
            pickup.pickupPrefab = _ammoPickups[randomId];
        }
        else
        {
            pickup.pickupType = PickupType.Weapon;
            pickup.pickupPrefab = _weaponPickups[randomId];
        }
    }
}
