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

public class LerpVolume : MonoBehaviour
{

    [SerializeField] private AudioSource source;

    private float originalVolume;
    private float targetVolume;
    private float timer = 0f;

    // Start is called before the first frame update
    void Start()
    {
        originalVolume = source.volume;
        targetVolume = source.volume;
    }

    // Update is called once per frame
    void Update()
    {
        if (source.volume != targetVolume)
        {
            source.volume = Mathf.Lerp(source.volume, targetVolume, Time.deltaTime);
            if (Mathf.Abs(source.volume - targetVolume) < .05)
            {
                source.volume = targetVolume;
            }
            Debug.Log($"New volume: {source.volume} Target: {targetVolume}");
        }
        else
        {
            Debug.Log($"Reached target volume of {targetVolume}, setting target to original volume of {originalVolume}");
            timer = Mathf.Clamp(timer - Time.deltaTime, 0, timer);
            if (timer == 0 && targetVolume != originalVolume)
            {
                targetVolume = originalVolume;
            }
        }
    }

    public void RaiseVolumeForTime(float target, float time)
    {
        Debug.Log($"Getting to {targetVolume} in {time}");
        timer = time;
        targetVolume = target;
    }
}
