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

public class FireBall : MonoBehaviour
{
    [SerializeField]
    private List<AudioResource> m_fireSounds;

    [SerializeField]
    private AudioSource m_audioSource;

    private bool m_markedForDestruction = false;

    private float m_lifeTime = 20f;
    private bool m_timer = true;

    public void LaunchFireBall(Vector3 direction, float force)
    {
        gameObject.SetActive(true);
        GetComponent<Rigidbody>().AddForce(direction * force, ForceMode.Impulse);

        m_audioSource.resource = m_fireSounds[Random.Range(0, m_fireSounds.Count)];
        m_audioSource.Play();
    }

    private void Update()
    {
        if (m_timer)
        {
            m_timer = false;
            m_lifeTime -= Time.deltaTime;
            if (m_lifeTime < 0)
            {
                m_markedForDestruction = true;
            }
        }

        if (m_markedForDestruction)
        {
            m_markedForDestruction = false;
            Destroy(gameObject);
        }
    }

    private IEnumerator DestroyBall()
    {
        yield return new WaitForSeconds(2f);
        m_markedForDestruction=true;
    }

    private void OnCollisionEnter(Collision collision)
    {
        StartCoroutine(DestroyBall());
    }
}
