using Microsoft.AspNetCore.Mvc;
using Hi.Disp;
using Hi.Geom;
using Hi.Webapi.Services;

namespace Sample.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class RenderingController : ControllerBase
    {
        private readonly RenderingService _renderingService;
        private readonly ILogger<RenderingController> _logger;

        public RenderingController(RenderingService renderingService, ILogger<RenderingController> logger)
        {
            _renderingService = renderingService;
            _logger = logger;
        }

        /// <summary>
        /// 獲取當前活動的渲染引擎數量
        /// </summary>
        [HttpGet("engines/count")]
        public IActionResult GetActiveEngineCount()
        {
            var count = _renderingService.GetActiveEngineCount();
            return Ok(new { count });
        }

        /// <summary>
        /// 創建測試用的 3D 對象
        /// </summary>
        [HttpPost("test-objects/{sessionId}")]
        public IActionResult CreateTestObjects(string sessionId)
        {
            _logger.LogInformation($"CreateTestObjects called - SessionId: {sessionId}");
            
            try
            {
                var engine = _renderingService.GetOrCreateEngine(sessionId);
                _logger.LogInformation($"Engine retrieved - SessionId: {sessionId}");
                
                // 創建一個簡單的測試顯示對象
                var testDisplayee = new TestDisplayee();
                engine.Displayee = testDisplayee;
                _logger.LogInformation($"TestDisplayee created and set - SessionId: {sessionId}");
                
                // 觸發一次渲染
                engine.IsVisible = true;
                _logger.LogInformation($"Engine visibility set to true to trigger render - SessionId: {sessionId}");
                
                return Ok(new { 
                    message = "Test objects created successfully",
                    sessionId = sessionId,
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error creating test objects - SessionId: {sessionId}");
                return StatusCode(500, new { 
                    error = ex.Message,
                    sessionId = sessionId,
                    timestamp = DateTime.Now
                });
            }
        }
    }

    /// <summary>
    /// 測試用的顯示對象
    /// </summary>
    public class TestDisplayee : IDisplayee
    {
        private readonly Drawing axesDrawing;
        private readonly Drawing cubeDrawing;
        private readonly Drawing groundDrawing;

        public TestDisplayee()
        {
            // 創建彩色坐標軸 (使用 CV stamp - Color + Vertex)
            double[] axesData = new double[] {
                // Red X-axis (color + vertex)
                1, 0, 0,  0, 0, 0,  // Red color, origin
                1, 0, 0,  200, 0, 0,  // Red color, x-axis end
                
                // Green Y-axis (color + vertex)
                0, 1, 0,  0, 0, 0,  // Green color, origin
                0, 1, 0,  0, 200, 0,  // Green color, y-axis end
                
                // Blue Z-axis (color + vertex)
                0, 0, 1,  0, 0, 0,  // Blue color, origin
                0, 0, 1,  0, 0, 200   // Blue color, z-axis end
            };
            
            axesDrawing = new Drawing(axesData, Stamp.CV, Hi.Disp.GL.GL_LINES);

            // 創建立方體線框 (使用 CV stamp - 帶顏色)
            var size = 100.0;
            var cubeData = new System.Collections.Generic.List<double>();
            
            // 黃色立方體
            var color = new[] { 1.0, 1.0, 0.0 }; // 黃色
            
            // 底面四條線
            AddColoredLine(cubeData, color, -size/2, -size/2, -size/2, size/2, -size/2, -size/2);
            AddColoredLine(cubeData, color, size/2, -size/2, -size/2, size/2, size/2, -size/2);
            AddColoredLine(cubeData, color, size/2, size/2, -size/2, -size/2, size/2, -size/2);
            AddColoredLine(cubeData, color, -size/2, size/2, -size/2, -size/2, -size/2, -size/2);
            
            // 頂面四條線
            AddColoredLine(cubeData, color, -size/2, -size/2, size/2, size/2, -size/2, size/2);
            AddColoredLine(cubeData, color, size/2, -size/2, size/2, size/2, size/2, size/2);
            AddColoredLine(cubeData, color, size/2, size/2, size/2, -size/2, size/2, size/2);
            AddColoredLine(cubeData, color, -size/2, size/2, size/2, -size/2, -size/2, size/2);
            
            // 垂直線
            AddColoredLine(cubeData, color, -size/2, -size/2, -size/2, -size/2, -size/2, size/2);
            AddColoredLine(cubeData, color, size/2, -size/2, -size/2, size/2, -size/2, size/2);
            AddColoredLine(cubeData, color, size/2, size/2, -size/2, size/2, size/2, size/2);
            AddColoredLine(cubeData, color, -size/2, size/2, -size/2, -size/2, size/2, size/2);
            
            cubeDrawing = new Drawing(cubeData.ToArray(), Stamp.CV, Hi.Disp.GL.GL_LINES);

            // 創建地面網格
            var gridData = new System.Collections.Generic.List<double>();
            var gridColor = new[] { 0.3, 0.3, 0.3 }; // 灰色
            var gridSize = 500.0;
            var gridStep = 50.0;
            
            for (double i = -gridSize; i <= gridSize; i += gridStep)
            {
                // X 方向的線
                AddColoredLine(gridData, gridColor, i, -gridSize, 0, i, gridSize, 0);
                // Y 方向的線
                AddColoredLine(gridData, gridColor, -gridSize, i, 0, gridSize, i, 0);
            }
            
            groundDrawing = new Drawing(gridData.ToArray(), Stamp.CV, Hi.Disp.GL.GL_LINES);
        }

        private void AddColoredLine(System.Collections.Generic.List<double> data, double[] color, 
            double x1, double y1, double z1, double x2, double y2, double z2)
        {
            // 第一個點
            data.Add(color[0]); data.Add(color[1]); data.Add(color[2]);
            data.Add(x1); data.Add(y1); data.Add(z1);
            // 第二個點
            data.Add(color[0]); data.Add(color[1]); data.Add(color[2]);
            data.Add(x2); data.Add(y2); data.Add(z2);
        }

        public void Display(Bind bind)
        {
            // 顯示地面網格
            groundDrawing.Display(bind);
            
            // 顯示坐標軸
            axesDrawing.Display(bind);
            
            // 顯示立方體
            cubeDrawing.Display(bind);
        }

        public void ExpandToBox3d(Box3d box)
        {
            // 擴展邊界框以包含我們的測試對象
            box.Expand(new Vec3d(-500, -500, -100));
            box.Expand(new Vec3d(500, 500, 200));
        }
    }
} 