using System;
using DG.Tweening;
using FairyGUI;
using UnityEngine;
using UnityEngine.Video;

namespace RedHotRoast
{
    public static class VideoPlayerHandover
    {
        private static VideoPlayer currentPlayer;
        private static Transform originalParent;
        private static GLoader originalLoader;

        /// <summary>
        /// 接管播放器，切换父物体和绑定loader
        /// </summary>
        public static void TakeOver(VideoPlayer player, Transform newParent, GLoader newLoader, Action callback = null)
        {
            if (player == null) return;

            currentPlayer = player;

            // 只记录第一次的父物体和loader（方便后面还原）
            if (originalParent == null)
                originalParent = player.transform.parent;
            if (originalLoader == null && newLoader != null)
                originalLoader = newLoader;

            // 切父物体
            player.transform.SetParent(newParent, false);

            // 绑定到新loader显示
            // if (newLoader != null)
            // {
            //     newLoader.texture = new NTexture(player.targetTexture);
            //     newLoader.visible = true;
            // }
            
            DOTween.To(()=>0, _=> {
                if (player.targetTexture != null)
                {
                    newLoader.texture = new NTexture(player.targetTexture);
                    newLoader.visible = true;
                }
                callback?.Invoke();
            }, 0, 0.05f); // 延迟0.05s
            
            // 播放状态不变，不暂停，不跳时间
        }

        /// <summary>
        /// 归还播放器到原父物体和loader
        /// </summary>
        public static void Return()
        {
            if (currentPlayer == null) return;

            // 切回原父物体
            currentPlayer.transform.SetParent(originalParent, false);

            // 绑定回原loader显示
            if (originalLoader != null)
            {
                if (currentPlayer.targetTexture == null)
                {
                    originalLoader.visible = false;
                }
                else
                {
                    originalLoader.texture = new NTexture(currentPlayer.targetTexture);
                    originalLoader.visible = true;
                }
            }

            // 播放状态保持不变

            // 清除引用，下次接管会重新记录
            currentPlayer = null;
            originalParent = null;
            originalLoader = null;
        }
    }
}
