using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Autodesk.Navisworks.Api;

namespace NavisworksTransport.Core
{
    /// <summary>
    /// 导航地图生成器 - 负责生成当前三维视图的截图并保存为图片文件
    /// </summary>
    public class NavigationMapGenerator
    {
        /// <summary>
        /// 生成当前文档的导航地图图像
        /// </summary>
        /// <param name="style">图像生成样式</param>
        /// <param name="width">图像宽度</param>
        /// <param name="height">图像高度</param>
        /// <param name="enableSectioning">是否启用剖面</param>
        /// <returns>生成的Bitmap图像</returns>
        public Bitmap GenerateNavigationMapImage(ImageGenerationStyle style, int width, int height, bool enableSectioning = false)
        {
            try
            {
                // 使用Navisworks API生成图像
                var doc = Application.ActiveDocument;
                Bitmap navigationMap = doc.GenerateImage(style, width, height, enableSectioning) ?? throw new InvalidOperationException("图像生成失败");
                LogManager.Debug($"导航地图生成成功: {width}x{height}像素");
                
                return navigationMap;
            }
            catch (Exception ex)
            {
                LogManager.Error($"生成导航地图失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存图像到指定路径和格式
        /// </summary>
        /// <param name="image">要保存的图像</param>
        /// <param name="filePath">保存路径</param>
        /// <param name="format">图像格式</param>
        public void SaveNavigationMapImage(Bitmap image, string filePath, ImageFormat format)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image), "图像不能为空");
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(nameof(filePath), "文件路径不能为空");
            }

            try
            {
                // 确保目录存在
                string directory = Path.GetDirectoryName(filePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // 保存图像
                image.Save(filePath, format);
            }
            catch (Exception ex)
            {
                LogManager.Error($"保存导航地图失败: {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取当前视窗的尺寸
        /// </summary>
        /// <returns>当前视窗尺寸（像素）</returns>
        /// <exception cref="InvalidOperationException">视窗尺寸无效时抛出</exception>
        public Size GetCurrentViewportSize()
        {
            var doc = Application.ActiveDocument;
            var view = doc.ActiveView;
            int width = view.Width;
            int height = view.Height;
            
            // 前置验证：确保尺寸有效
            if (width <= 0 || height <= 0)
                throw new InvalidOperationException($"无效的视窗尺寸: {width}x{height}");
            
            LogManager.Info($"获取视窗尺寸: {width}x{height}");
            return new Size(width, height);
        }

        /// <summary>
        /// 根据文件扩展名获取对应的ImageFormat
        /// </summary>
        /// <param name="extension">文件扩展名（包含点号）</param>
        /// <returns>对应的ImageFormat</returns>
        public static ImageFormat GetImageFormatFromExtension(string extension)
        {
            if (string.IsNullOrEmpty(extension))
            {
                return ImageFormat.Png; // 默认PNG格式
            }

            extension = extension.ToLowerInvariant();
            if (extension == ".jpg" || extension == ".jpeg")
            {
                return ImageFormat.Jpeg;
            }
            else if (extension == ".png")
            {
                return ImageFormat.Png;
            }
            else if (extension == ".bmp")
            {
                return ImageFormat.Bmp;
            }
            else
            {
                return ImageFormat.Png; // 默认PNG格式
            }
        }

        /// <summary>
        /// 验证当前环境是否可以生成导航地图
        /// </summary>
        /// <returns>true表示可以生成，false表示不能生成</returns>
        public bool CanGenerateNavigationMap()
        {
            try
            {
                Document activeDocument = Application.ActiveDocument;
                return activeDocument != null && !activeDocument.IsClear;
            }
            catch (Exception ex)
            {
                LogManager.Error($"检查导航地图生成条件失败: {ex.Message}", ex);
                return false;
            }
        }
    }
}