using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Autodesk.Navisworks.Api;

namespace NavisworksTransport.Utils.CoordinateSystem
{
    /// <summary>
    /// 当前文档运行时 key 缓存。
    /// 用于"模型根旋转提示"等按文档去重的交互（同一文档只提示一次）。
    /// 原名 FragmentDefaultUpContext（曾承担 fragment 默认 Up 运行时状态），
    /// 0.18.2 去掉 fragment 参考姿态依赖后，仅保留文档 key 功能。
    /// </summary>
    internal static class DocumentKeyContext
    {
        private static readonly ConcurrentDictionary<int, string> RuntimeDocumentKeys =
            new ConcurrentDictionary<int, string>();

        public static string GetCurrentDocumentKey(Document doc = null)
        {
            doc = doc ?? Autodesk.Navisworks.Api.Application.ActiveDocument;
            if (doc == null || doc.IsClear)
            {
                return string.Empty;
            }

            int runtimeDocumentId = RuntimeHelpers.GetHashCode(doc);
            return GetOrCreateDocumentKey(runtimeDocumentId, doc.FileName, doc.Title);
        }

        internal static string GetOrCreateDocumentKey(int runtimeDocumentId, string fileName, string title)
        {
            if (runtimeDocumentId <= 0)
            {
                return string.Empty;
            }

            if (RuntimeDocumentKeys.TryGetValue(runtimeDocumentId, out string existingKey) &&
                !string.IsNullOrWhiteSpace(existingKey))
            {
                return existingKey;
            }

            string resolvedKey;
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                resolvedKey = $"file:{fileName}";
            }
            else if (!string.IsNullOrWhiteSpace(title))
            {
                resolvedKey = $"runtime:{runtimeDocumentId}|title:{title}";
            }
            else
            {
                resolvedKey = $"runtime:{runtimeDocumentId}";
            }

            RuntimeDocumentKeys[runtimeDocumentId] = resolvedKey;
            return resolvedKey;
        }

        internal static void ResetForTests()
        {
            RuntimeDocumentKeys.Clear();
        }
    }
}
