using System.Drawing;
using System.Text;
using SparkClient.Model.Attributes;
using SparkClient.Model.Helper;
using SparkDotNetCore.ArrowAndHeart;
using SparkDotNetCore.ArrowAndHeart.Entity;

namespace SparkClient.Views.UserControl.ViewportData.Helper;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;
public class RayHelper
{
    //unity渲染结果(运行前清理)
    private static string _image_path = AppDomain.CurrentDomain.BaseDirectory + @"Ray\Image\"; 
    //unity渲染模型缓存(运行前清理)
    private static string _obj_path = AppDomain.CurrentDomain.BaseDirectory + @"Ray\Obj"; 
    [Log]
    public static void GenerateRender(string modelInfo, string diamondCode)
    {
        string fileName = GenerateSignature(modelInfo, diamondCode);
        string fullStlPath = Path.Combine(_obj_path, fileName);

        // 1. 检查STL文件是否存在
        if (File.Exists(fullStlPath))
        {
            if (ValidateImages())
            {
                ShowImages();
                return;
            }
        }

        // 2. 清理Unity相关目录
        CleanDirectory(_image_path);
        CleanDirectory(_obj_path);

        // 3. 导出模型为STL
        ObjExporter.ExportToObj2(ViewportManager.ViewportTriangle, fullStlPath + ".obj");
        // 4. 执行Unity渲染命令两次
        string fullObjPath = fullStlPath + ".obj";
        string heartImagePath = _image_path + @"Heart.png";
        string arrowImagePath = _image_path + @"Arrow.png";
        RayTracingInput rayTracingInput = new RayTracingInput { 
            Obj = fullObjPath,
            Arrow = arrowImagePath,
            Heart = heartImagePath,
        };
        DiamondRayTracing diamondRayTracing = new DiamondRayTracing(rayTracingInput);
        RayTracingResult result = diamondRayTracing.Render();
        if (result!= null && "OK".Equals(result.Status)) {
            ShowImages();
        } else {
            throw new Exception(MultilingualHelper.getString("RayTracingGenError"));
        }
 
    }
    [Log]
    private static string GenerateSignature(string modelInfo, string diamondCode)
    {
        // 模拟生成签名逻辑,可以自定义为更复杂的算法
        return modelInfo;
    }
    [Log]
    private static void CleanDirectory(string path)
    {
        if (Directory.Exists(path))
        {
            Directory.Delete(path, true);
        }
        Directory.CreateDirectory(path);
    }

    // private static void ExportModelsToStl(string path)
    // {
    //
    //     ViewportHelperPro.ExportModelsToStl(null, path);
    // }

    // private static void ExecuteUnityRendering(string fileName, int type)
    // {
    //     string arguments = $@"--obj {_obj_path + @"\" + fileName + ".obj"} --output {_image_path}{type}.jpg --mode {type}";
    //     string exePath = Path.Combine(_unity_path, "hart.exe");
    //
    //     if (!File.Exists(exePath))
    //     {
    //         throw new FileNotFoundException(MultilingualHelper.getString("RayTracingNoPlugin"), exePath);
    //     }
    //
    //     using (Process process = new Process())
    //     {
    //         process.StartInfo.FileName = exePath;
    //         process.StartInfo.Arguments = arguments;
    //         process.StartInfo.UseShellExecute = false;
    //         process.StartInfo.CreateNoWindow = true;
    //         process.StartInfo.RedirectStandardOutput = true;
    //         process.StartInfo.RedirectStandardError = true;
    //
    //         // 使用StringBuilder来捕获输出和错误信息
    //         StringBuilder outputBuilder = new StringBuilder();
    //         StringBuilder errorBuilder = new StringBuilder();
    //
    //         process.OutputDataReceived += (sender, e) => 
    //         {
    //             if (e.Data != null)
    //                 outputBuilder.AppendLine(e.Data);
    //         };
    //         process.ErrorDataReceived += (sender, e) => 
    //         {
    //             if (e.Data != null)
    //                 errorBuilder.AppendLine(e.Data);
    //         };
    //
    //         process.Start();
    //
    //         // 开始异步读取输出和错误流
    //         process.BeginOutputReadLine();
    //         process.BeginErrorReadLine();
    //
    //         process.WaitForExit();
    //
    //         // 获取完整的输出和错误信息
    //         string outputMsg = outputBuilder.ToString();
    //         string errorMsg = errorBuilder.ToString();
    //         errorMsg = string.IsNullOrWhiteSpace(errorMsg)?outputMsg:errorMsg;
    //         if (process.ExitCode != 0)
    //         {
    //             throw new Exception($"{MultilingualHelper.getString("RayTracingFail")}{errorMsg}");
    //         }
    //     }
    // }
    [Log]
    private static bool ValidateImages()
    {
        string heartImage = Path.Combine(_image_path, @"Heart.png");
        string arrowImage = Path.Combine(_image_path,  @"Arrow.png");

        return File.Exists(heartImage) && File.Exists(arrowImage);
    }
    [Log]
    private static void ShowImages()
    {
        // 创建一个简单的图片展示窗口
        Form form = new Form
        {
            Text = MultilingualHelper.getString("RayTracingFormTitle"),
            Width = 800,
            Height = 450,
            MaximizeBox = false,
            MinimizeBox = false,
            BackColor = Color.Black,
            StartPosition = FormStartPosition.CenterScreen,
        };

        PictureBox heartBox = new PictureBox
        {
            ImageLocation = Path.Combine(_image_path, "Heart.png"),
            SizeMode = PictureBoxSizeMode.Zoom,
            Dock = DockStyle.Left,
            Width = 400
        };

        PictureBox arrowBox = new PictureBox
        {
            ImageLocation = Path.Combine(_image_path, "Arrow.png"),
            SizeMode = PictureBoxSizeMode.Zoom,
            Dock = DockStyle.Right,
            Width = 400
        };

        form.Controls.Add(heartBox);
        form.Controls.Add(arrowBox);

        Label label = new Label
        {
            Text = MultilingualHelper.getString("RayTracingFormMessage"),
            Dock = DockStyle.Bottom,
            Height = 30,
            TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
            ForeColor = Color.WhiteSmoke,
        };

        form.Controls.Add(label);
        form.ShowDialog();
    }
}