using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;

public class ModularGun : MonoBehaviour
{
    [SerializeField] int numberOfRoundsPerReload = 5;
    [SerializeField] float timeBetweenRounds = 1;

    [Space]
    [SerializeField] int numberOfBulletsPerRound = 4;
    [SerializeField] float timeBetweenBullets = 0.1f;

    private Coroutine firingRoundsCoroutine = null;

    private IEnumerator FireBullets()
    {
        int numberOfBulletsFired = 0;

        while (numberOfBulletsFired < numberOfBulletsPerRound)
        {
            Debug.Log($"Bullet Fired");

            yield return new WaitForSecondsRealtime(timeBetweenBullets);

            numberOfBulletsFired++;
        }

        Debug.Log("Round Empty");
    }

    private IEnumerator FireRounds()
    {
        Debug.Log("Preparing to fire Rounds");

        int numberOfRoundsFired = 0;

        while (numberOfRoundsFired < numberOfRoundsPerReload)
        {
            Debug.Log($"<color=yellow>Firing Round</color>");

            StartCoroutine(FireBullets());

            yield return new WaitForSecondsRealtime(timeBetweenRounds);

            numberOfRoundsFired++;
        }
    }

    public void PrimaryFire(InputAction.CallbackContext context)
    {
        if (context.action.phase == InputActionPhase.Started)
        {
            Debug.Log("<color=green>Primary Fire Pressed</color>");
            firingRoundsCoroutine = StartCoroutine(FireRounds());
        }
        else if (context.action.phase == InputActionPhase.Canceled)
        {
            Debug.Log("<color=red>Primary Fire Released</color>");
            StopCoroutine(firingRoundsCoroutine);
        }
    }

}