using UnityEngine;

namespace Saltosion.OneWeapon.Audio {
    [RequireComponent(typeof(AudioSource))]
    public class MusicChannelPlayer : MonoBehaviour {
        public bool FadingOut;
        public bool FadingIn;
        public float FadeDuration;
        public AudioClip NextClip;
        public float Volume;
        public bool Loop;
        public bool CurrentlyPlaying { get { return Source.clip != null; } }

        private AudioSource Source;

        private void Start() {
            Source = GetComponent<AudioSource>();
        }

        private void Update() {
            if (!FadingOut && !FadingIn) {
                Source.volume = Volume;
            } else if (FadingIn && Source.clip == null) {
                Source.clip = NextClip;
                Source.loop = Loop;
                if (Source.clip != null) {
                    Source.Play();
                }
                NextClip = null;
            } else if (FadingOut && Source.volume > 0) {
                Source.volume = Mathf.Clamp(Source.volume - Time.deltaTime / FadeDuration / Volume, 0, Volume);
            } else if (FadingOut && Source.volume == 0) {
                Source.Stop();
                Source.clip = null;
                FadingOut = false;
            } else if (FadingIn && Source.volume < Volume) {
                Source.volume = Mathf.Clamp(Source.volume + Time.deltaTime / FadeDuration / Volume, 0, Volume);
            } else if (FadingIn && Source.volume == Volume) {
                FadingIn = false;
            }
        }
    }
}
