namespace NavisworksTransport.Core.UIUpdate.Updates
{
    /// <summary>
    /// Action包装更新操作
    /// 将普通的Action包装为UI更新操作，提供线程安全的执行环境
    /// </summary>
    public class ActionWrapperUpdateOperation : UIUpdateBase
    {
        #region 字段和属性

        /// <summary>
        /// 要执行的Action
        /// </summary>
        public Action Action { get; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化Action包装更新操作
        /// </summary>
        /// <param name="name">操作名称</param>
        /// <param name="action">要执行的Action</param>
        /// <param name="priority">操作优先级</param>
        /// <param name="targetFramework">目标框架</param>
        public ActionWrapperUpdateOperation(string name, Action action, UIUpdatePriority priority = UIUpdatePriority.Normal, UIFrameworkType targetFramework = UIFrameworkType.Auto)
            : base(name, $"执行Action: {name}", priority, targetFramework)
        {
            Action = action ?? throw new ArgumentNullException(nameof(action));
            SupportsRollback = false; // Action操作默认不支持回滚
        }

        #endregion

        #region 受保护方法重写

        /// <summary>
        /// 内部验证逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <returns>验证结果</returns>
        protected override UIUpdateValidationResult ValidateInternal(UIUpdateContext context)
        {
            if (Action == null)
            {
                return UIUpdateValidationResult.Failure("Action不能为空");
            }

            return UIUpdateValidationResult.Success();
        }

        /// <summary>
        /// 执行主要逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>执行结果</returns>
        protected override async Task<UIUpdateResult> ExecuteInternalAsync(UIUpdateContext context, CancellationToken cancellationToken)
        {
            try
            {
                LogInfo($"执行Action包装操作: {Name}");

                // 使用UIStateManager确保在适当的线程上执行
                var uiStateManager = UIStateManager.Instance;

                if (RequiresUIThread)
                {
                    await uiStateManager.ExecuteUIUpdateAsync(Action, context.TimeoutMilliseconds);
                }
                else
                {
                    // 如果不需要UI线程，直接执行
                    await Task.Run(() =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        Action();
                    }, cancellationToken);
                }

                LogInfo($"成功执行Action包装操作: {Name}");
                return UIUpdateResult.Success($"成功执行Action: {Name}", Id);
            }
            catch (OperationCanceledException)
            {
                LogWarning($"Action包装操作被取消: {Name}");
                return UIUpdateResult.Failure("操作被取消", null, Id);
            }
            catch (Exception ex)
            {
                LogError($"执行Action包装操作{Name}失败", ex);
                return UIUpdateResult.Failure($"执行失败: {ex.Message}", ex, Id);
            }
        }

        #endregion
    }

    /// <summary>
    /// Func包装更新操作
    /// 将普通的Func包装为UI更新操作，提供线程安全的执行环境
    /// </summary>
    /// <typeparam name="T">返回值类型</typeparam>
    public class FuncWrapperUpdateOperation<T> : UIUpdateBase
    {
        #region 字段和属性

        /// <summary>
        /// 要执行的Func
        /// </summary>
        public Func<T> Func { get; }

        /// <summary>
        /// 执行结果
        /// </summary>
        public T Result { get; private set; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化Func包装更新操作
        /// </summary>
        /// <param name="name">操作名称</param>
        /// <param name="func">要执行的Func</param>
        /// <param name="priority">操作优先级</param>
        /// <param name="targetFramework">目标框架</param>
        public FuncWrapperUpdateOperation(string name, Func<T> func, UIUpdatePriority priority = UIUpdatePriority.Normal, UIFrameworkType targetFramework = UIFrameworkType.Auto)
            : base(name, $"执行Func: {name}", priority, targetFramework)
        {
            Func = func ?? throw new ArgumentNullException(nameof(func));
            SupportsRollback = false; // Func操作默认不支持回滚
        }

        #endregion

        #region 受保护方法重写

        /// <summary>
        /// 内部验证逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <returns>验证结果</returns>
        protected override UIUpdateValidationResult ValidateInternal(UIUpdateContext context)
        {
            if (Func == null)
            {
                return UIUpdateValidationResult.Failure("Func不能为空");
            }

            return UIUpdateValidationResult.Success();
        }

        /// <summary>
        /// 执行主要逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>执行结果</returns>
        protected override async Task<UIUpdateResult> ExecuteInternalAsync(UIUpdateContext context, CancellationToken cancellationToken)
        {
            try
            {
                LogInfo($"执行Func包装操作: {Name}");

                // 使用UIStateManager确保在适当的线程上执行
                var uiStateManager = UIStateManager.Instance;

                if (RequiresUIThread)
                {
                    Result = await uiStateManager.ExecuteUIUpdateAsync(Func, context.TimeoutMilliseconds);
                }
                else
                {
                    // 如果不需要UI线程，直接执行
                    Result = await Task.Run(() =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        return Func();
                    }, cancellationToken);
                }

                LogInfo($"成功执行Func包装操作: {Name}，结果: {Result}");
                
                var result = UIUpdateResult.Success($"成功执行Func: {Name}", Id);
                result.Data["Result"] = Result;
                return result;
            }
            catch (OperationCanceledException)
            {
                LogWarning($"Func包装操作被取消: {Name}");
                return UIUpdateResult.Failure("操作被取消", null, Id);
            }
            catch (Exception ex)
            {
                LogError($"执行Func包装操作{Name}失败", ex);
                return UIUpdateResult.Failure($"执行失败: {ex.Message}", ex, Id);
            }
        }

        #endregion
    }
}