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

[RequireComponent(typeof(PlayerInput))]
public class ModularGun : MonoBehaviour
{
    [SerializeField] int maximumNumberOfRounds;
    [SerializeField] int numberOfFiresPerRound;
    [SerializeField] float timeBetweenRounds;
    [SerializeField] float timeBetweenFires;

    private PlayerInput playerInput;

    private WaitForSecondsRealtime timeBetweenFiresWaiter;
    private WaitForSecondsRealtime timeBetweenRoundsWaiter;

    private Coroutine firingBullets = null;
    private Coroutine fireRoundsCoroutine = null;

    private void Awake()
    {
        playerInput = GetComponent<PlayerInput>();

        timeBetweenFiresWaiter = new WaitForSecondsRealtime(timeBetweenFires);
        timeBetweenRoundsWaiter = new WaitForSecondsRealtime(timeBetweenRounds);
    }

    // Called to fire a single bullet
    private void Fire()
    {
        Debug.Log("Bullet Fired");
    }

    private IEnumerator FireBullets()
    {
        int numberOfBulletsFired = 0;

        while (numberOfBulletsFired < numberOfFiresPerRound)
        {
            Fire();

            yield return timeBetweenFiresWaiter;

            numberOfBulletsFired++;
        }

        firingBullets = null;
    }

    // Called to fire a complete round of bullets
    public void FireRound()
    {
        Debug.Log("<color=yellow>Round Started</color>");

        StartCoroutine(FireBullets());
    }

    private IEnumerator FireRounds()
    {
        int roundsFired = 0;
        firingBullets = null;

        var stillFiringBullets = new WaitUntil(() => firingBullets == null);
        while (roundsFired < maximumNumberOfRounds)
        {
            Debug.Log("<color=yellow>Round Started</color>");

            firingBullets = StartCoroutine(FireBullets());

            yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime - Minimum wait time
            yield return stillFiringBullets;//Wait till done firing
            roundsFired++;
        }
    }

    public void PrimaryFire(InputAction.CallbackContext context)
    {
        if (context.action.phase == InputActionPhase.Started)
        {
            Debug.Log("<color=green>Firing Rounds</color>");
            fireRoundsCoroutine = StartCoroutine(FireRounds());
        }

        else if (context.action.phase == InputActionPhase.Canceled)
        {
            Debug.Log("<color=red>Stopping Fire</color>");
            if (fireRoundsCoroutine != null)
            {
                StopCoroutine(fireRoundsCoroutine);
                fireRoundsCoroutine = null;
            }
            else Debug.Log("Fire Rounds Coroutine is Null");
        }
    }
}