using System.Threading;
using Cysharp.Threading.Tasks;
using Darkmatter.Core.Contracts.Services.Scenes;
using Darkmatter.Core.Enums.Services.Scenes;
using Darkmatter.Features.AppBoot.SceneRefs;
using UnityEngine;
using UnityEngine.Video;
using VContainer.Unity;

namespace Darkmatter.Features.AppBoot.Flow
{
    public class AppBootFlow : IAsyncStartable
    {
        private readonly AppBootSceneRefs _sceneRefs;
        private readonly ISceneService _sceneService;

        public AppBootFlow(AppBootSceneRefs sceneRefs, ISceneService sceneService)
        {
            _sceneRefs = sceneRefs;
            _sceneService = sceneService;
        }

        public async UniTask StartAsync(CancellationToken cancellation = default)
        {
            var tcs = new UniTaskCompletionSource();
            var player = _sceneRefs.IntroVideoPlayer;

            void OnDone(VideoPlayer vp)
            {
                vp.loopPointReached -= OnDone;
                tcs.TrySetResult();
            }

            player.loopPointReached += OnDone;
            player.Play();
            await _sceneService.LoadSceneAsync(GameScene.MainMenu, null, cancellation);

            await tcs.Task.AttachExternalCancellation(cancellation);

            player.Stop();
            var rt = player.targetTexture;
            if (rt != null) rt.Release();

            if (_sceneRefs.IntroCanvas != null)
                Object.Destroy(_sceneRefs.IntroCanvas.gameObject);
            Object.Destroy(player.gameObject);
        }
    }
}