using System;
using Autodesk.Navisworks.Api;
using NavisApplication = Autodesk.Navisworks.Api.Application;

namespace NavisworksTransport.Core
{
    /// <summary>
    /// 文档状态管理器，统一管理文档生命周期和状态变化
    /// </summary>
    public class DocumentStateManager
    {
        private static DocumentStateManager _instance;
        private static readonly object _lock = new object();
        
        private Document _currentDocument;
        private bool _isDocumentValid;
        private string _currentDocumentPath;
        
        /// <summary>
        /// 文档已失效事件
        /// </summary>
        public event EventHandler DocumentInvalidated;
        
        /// <summary>
        /// 文档已就绪事件
        /// </summary>
        public event EventHandler DocumentReady;
        
        /// <summary>
        /// 获取单例实例
        /// </summary>
        public static DocumentStateManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new DocumentStateManager();
                        }
                    }
                }
                return _instance;
            }
        }
        
        private DocumentStateManager()
        {
            // 私有构造函数
            _isDocumentValid = false;
        }
        
        /// <summary>
        /// 获取当前文档是否有效
        /// </summary>
        public bool IsDocumentValid => _isDocumentValid;
        
        /// <summary>
        /// 获取当前文档
        /// </summary>
        public Document CurrentDocument => _currentDocument;
        
        /// <summary>
        /// 获取当前文档路径
        /// </summary>
        public string CurrentDocumentPath => _currentDocumentPath;
        
        /// <summary>
        /// 文档失效时调用
        /// </summary>
        public void OnDocumentInvalidated()
        {
            try
            {
                LogManager.Info("[DocumentStateManager] 文档失效通知");
                
                _isDocumentValid = false;
                _currentDocument = null;
                _currentDocumentPath = null;
                
                // 触发文档失效事件
                DocumentInvalidated?.Invoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[DocumentStateManager] 处理文档失效失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 文档就绪时调用
        /// </summary>
        public void OnDocumentReady()
        {
            try
            {
                // 验证新文档
                _currentDocument = NavisApplication.ActiveDocument;
                
                if (_currentDocument != null)
                {
                    _isDocumentValid = true;
                    _currentDocumentPath = _currentDocument.FileName;
                    
                    LogManager.Info($"[DocumentStateManager] 文档就绪: {_currentDocumentPath ?? "未保存的文档"}");
                    
                    // 触发文档就绪事件
                    DocumentReady?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    LogManager.Warning("[DocumentStateManager] 没有活动文档");
                    _isDocumentValid = false;
                    _currentDocumentPath = null;
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[DocumentStateManager] 处理文档就绪失败: {ex.Message}");
                _isDocumentValid = false;
            }
        }
        
        /// <summary>
        /// 验证当前文档是否仍然有效
        /// </summary>
        public bool ValidateCurrentDocument()
        {
            try
            {
                if (!_isDocumentValid || _currentDocument == null)
                    return false;
                
                // 检查文档是否仍然是活动文档
                var activeDoc = NavisApplication.ActiveDocument;
                if (activeDoc == null || activeDoc != _currentDocument)
                {
                    LogManager.Warning("[DocumentStateManager] 当前文档已不是活动文档");
                    _isDocumentValid = false;
                    return false;
                }
                
                // 尝试访问文档属性以验证其有效性
                var fileName = activeDoc.FileName;
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[DocumentStateManager] 文档验证失败: {ex.Message}");
                _isDocumentValid = false;
                return false;
            }
        }
        
        /// <summary>
        /// 验证ModelItem是否属于当前有效文档
        /// </summary>
        public bool IsModelItemValid(ModelItem item)
        {
            if (item == null)
                return false;
            
            if (!_isDocumentValid)
                return false;
            
            try
            {
                // 尝试访问ModelItem的属性
                var name = item.DisplayName;
                var hasGeometry = item.HasGeometry;
                return true;
            }
            catch (Exception)
            {
                // 如果访问属性时出错，说明对象已失效
                return false;
            }
        }
        
        /// <summary>
        /// 安全执行需要有效文档的操作
        /// </summary>
        public T SafeExecuteWithDocument<T>(Func<Document, T> action, T defaultValue = default)
        {
            try
            {
                if (!ValidateCurrentDocument())
                {
                    LogManager.Warning("[DocumentStateManager] 文档无效，操作被取消");
                    return defaultValue;
                }
                
                return action(_currentDocument);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[DocumentStateManager] 执行文档操作失败: {ex.Message}");
                return defaultValue;
            }
        }
        
        /// <summary>
        /// 安全执行需要有效文档的操作（无返回值）
        /// </summary>
        public void SafeExecuteWithDocument(Action<Document> action)
        {
            SafeExecuteWithDocument(doc =>
            {
                action(doc);
                return true;
            }, false);
        }
        
        /// <summary>
        /// 清理资源
        /// </summary>
        public void Dispose()
        {
            try
            {
                // 清空事件订阅者
                DocumentInvalidated = null;
                DocumentReady = null;
                
                _currentDocument = null;
                _isDocumentValid = false;
                _currentDocumentPath = null;
                
                LogManager.Info("[DocumentStateManager] 资源已清理");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[DocumentStateManager] 清理资源失败: {ex.Message}");
            }
        }
    }
}