using System;
using System.Threading;
using System.Windows;

namespace NavisworksTransport
{
    /// <summary>
    /// 剪贴板工具方法
    /// </summary>
    public static class ClipboardHelper
    {
        private const int MaxAttempts = 6;
        private const int RetryDelayMilliseconds = 80;

        /// <summary>
        /// 尝试写入文本到剪贴板
        /// </summary>
        public static bool TrySetText(string text, string context = null)
        {
            string clipboardText = text ?? string.Empty;
            Exception lastException = null;

            for (int attempt = 0; attempt < MaxAttempts; attempt++)
            {
                if (TrySetTextOnStaThread(clipboardText, out lastException))
                {
                    return true;
                }

                if (attempt < MaxAttempts - 1)
                {
                    Thread.Sleep(RetryDelayMilliseconds);
                }
            }

            string prefix = string.IsNullOrWhiteSpace(context) ? "[剪贴板]" : $"[{context}]";
            LogManager.Debug($"{prefix} 写入剪贴板失败: {lastException?.Message ?? "未知错误"}");
            return false;
        }

        private static bool TrySetTextOnStaThread(string text, out Exception exception)
        {
            bool success = false;
            Exception capturedException = null;

            Thread thread = new Thread(() =>
            {
                try
                {
                    Clipboard.SetDataObject(text, true);
                    success = true;
                }
                catch (Exception ex)
                {
                    capturedException = ex;
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
            thread.Join();

            exception = capturedException;
            return success;
        }
    }
}
