using UnityEngine;
using System.Collections;

public class Multiplier : MonoBehaviour
{
    public AudioClip multiplierSound;

    public AudioClip missedSound;

    public AudioClip gotItSound;

    public AudioClip gotHalfSound;

    private int multiplierValue = 0;

    private float multiplierTimer = 0f;

    private float stateTimer = 0f;

    private bool isActive = true;

    private AudioSource audioSource;

    private Animator multiplierAnimator;

    private SpriteRenderer multiplierSpriteRenderer;

    private static float stateDuration = 0.5f;

    private static float multiplierDuration = 30f;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        audioSource = GetComponent<AudioSource>();        
        multiplierAnimator = GetComponent<Animator>();
        multiplierSpriteRenderer = GetComponent<SpriteRenderer>();

        audioSource.PlayOneShot(multiplierSound);
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        stateTimer += Time.fixedDeltaTime;
        multiplierTimer += Time.fixedDeltaTime;

        if (stateTimer >= stateDuration)
        {
            stateTimer = 0f;
            multiplierValue = (multiplierValue + 1) % 4;
            multiplierAnimator.SetInteger("bonus", multiplierValue + 1);
        }

        if (multiplierTimer >= multiplierDuration && isActive)
        {
            isActive = false;
            audioSource.PlayOneShot(missedSound);
            multiplierSpriteRenderer.enabled = false;
            StartCoroutine(DestroyAfterDelay());
        }
    }

    private IEnumerator DestroyAfterDelay()
    {
        yield return new WaitForSeconds(1.5f);
        Destroy(gameObject);
    }

    public void AwardToPlayer(Player player)
    {
        if (isActive)
        {
            isActive = false;
            if (multiplierValue == 0)
            {
                audioSource.PlayOneShot(gotHalfSound);
                player.multiplier = 0.5f;
            }
            else
            {
                audioSource.PlayOneShot(gotItSound);
                player.multiplier = (float)(multiplierValue + 1);
            }

            multiplierSpriteRenderer.enabled = false;
            StartCoroutine(DestroyAfterDelay());
        }
    }
}
