using System;
using System.Collections.Generic;
using Darkmatter.Core.Enums.Services.Audio;
using UnityEngine;

namespace Darkmatter.Core.Data.Static.Services.Audio
{
    [CreateAssetMenu(fileName = "SfxCatalog", menuName = "Darkmatter/Audio/Sfx Catalog")]
    public class SfxCatalogSO : ScriptableObject
    {
        [Serializable]
        public class Entry
        {
            public SfxId Id;
            public AudioClip Clip;
            public AudioChannel Channel = AudioChannel.Sfx;
            [Range(0f, 1f)] public float Volume = 1f;
            [Range(0.1f, 3f)] public float Pitch = 1f;
            public bool Loop;
        }

        [SerializeField] private List<Entry> entries = new();

        private Dictionary<SfxId, Entry> _index;

        public bool TryGet(SfxId id, out Entry entry)
        {
            if (_index == null) BuildIndex();
            return _index.TryGetValue(id, out entry);
        }

        private void BuildIndex()
        {
            _index = new Dictionary<SfxId, Entry>(entries.Count);
            foreach (var e in entries)
            {
                if (e != null && e.Id != SfxId.None && e.Clip != null)
                    _index[e.Id] = e;
            }
        }

        private void OnValidate() => _index = null;
    }
}
