using Darkmatter.Core.Contracts.Services.Audio;
using Darkmatter.Core.Data.Dynamic.Services.Audio;
using Darkmatter.Core.Data.Static.Services.Audio;
using Darkmatter.Core.Enums.Services.Audio;
using UnityEngine;

namespace Darkmatter.Services.Audio
{
    public class SfxPlayer : ISfxPlayer
    {
        private readonly IAudioService _audioService;
        private readonly SfxCatalogSO _catalog;

        public SfxPlayer(IAudioService audioService, SfxCatalogSO catalog)
        {
            _audioService = audioService;
            _catalog = catalog;
        }

        public AudioHandle Play(SfxId id, Transform follow = null) => PlayInternal(id, follow, forceLoop: false);

        public AudioHandle PlayLoop(SfxId id, Transform follow = null) => PlayInternal(id, follow, forceLoop: true);

        public void Stop(AudioHandle handle, float fadeOutSeconds = 0f) => _audioService.Stop(handle, fadeOutSeconds);

        public bool IsPlaying(AudioHandle handle) => _audioService.IsPlaying(handle);

        private AudioHandle PlayInternal(SfxId id, Transform follow, bool forceLoop)
        {
            if (_catalog == null || !_catalog.TryGet(id, out var entry))
            {
                Debug.LogWarning($"[SfxPlayer] No catalog entry for {id}");
                return AudioHandle.Invalid;
            }

            bool loop = forceLoop || entry.Loop;
            var request = new AudioRequest(
                clip: entry.Clip,
                channel: entry.Channel,
                mode: loop ? AudioPlayMode.Loop : AudioPlayMode.OneShot,
                stopChannelBeforePlay: false,
                volume01: entry.Volume,
                pitch: entry.Pitch,
                spatial3D: false,
                followTarget: follow);

            return _audioService.Play(request);
        }
    }
}