using HutongGames.PlayMaker;
using System.Threading.Tasks;
using UnityEngine;

namespace BansheeGz.BGDatabase
{
    [ActionCategory("BansheeGz")]
    [HutongGames.PlayMaker.Tooltip("Asynchronously release all addressable assets cached under the specified group name, then fire event.")]
    public class BGAddressablesReleaseGroupCache : FsmStateAction
    {
        [UIHint(UIHint.FsmString)]
        [HutongGames.PlayMaker.Tooltip("Cache group name to release")]
        public FsmString CacheGroup;

        [HutongGames.PlayMaker.Tooltip("Event to send once the group is released")]
        public FsmEvent ReleasedEvent;

        public override void Reset()
        {
            CacheGroup = null;
            ReleasedEvent = null;
        }

        public override void OnEnter()
        {
            var group = CacheGroup.IsNone || string.IsNullOrEmpty(CacheGroup.Value) ? "Default" : CacheGroup.Value;
            ReleaseGroupAsync(group);
        }

        private async void ReleaseGroupAsync(string group)
        {
            await Task.Yield(); // Can be replaced with Task.Delay(1) or chunked release logic
            BGAddressablesAssetCache.ReleaseGroup(group);
            Fsm.Event(ReleasedEvent);
            Finish();
        }
    }
}
