using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FMOD;
using FMOD.Studio;
using FMODUnity;

[RequireComponent(typeof(FMODUnity.StudioBankLoader))]
public class AudioManager : MonoBehaviour
{
    [System.Serializable]
    private struct AdjustableAudioBus
    {
        public string BusName;
        public PlayerPrefValue PlayerPref;

        public void Initialise()
        {
            var bus = FMODUnity.RuntimeManager.GetBus( $"bus:/{BusName}" );
            PlayerPref.OnFloatSet.AddListener( (vol) => bus.setVolume(vol) );
            bus.setVolume( PlayerPref.GetFloat( 1.0f ) );
        }
    }
    
    [SerializeField]
    [EventRef]
    private string _musicId;

    [SerializeField]
    private AdjustableAudioBus _musicBus;
    
    [SerializeField]
    private AdjustableAudioBus _sfxBus;
    
    [SerializeField]
    private AdjustableAudioBus _voBus;
    
    [SerializeField]
    private AdjustableAudioBus _uiBus;
    
    public AudioManager Instance { get; private set; }
    
    private EventInstance _musicInstance;

    void Awake()
    {
        if ( Instance != null )
        {
            Destroy( gameObject );
            return;
        }

        Instance = this;

        GetComponent<StudioBankLoader>().enabled = true;
        
        _musicInstance = RuntimeManager.CreateInstance( _musicId );
        _musicInstance.start();
        
        _musicBus.Initialise();
        _sfxBus.Initialise();
        _voBus.Initialise();
        _uiBus.Initialise();
    }
}
