using UnityEngine;
using UnityEditor;
using IndianOceanAssets.Engine2_5D;

/// <summary>
/// 遮罩平面调整工具
/// </summary>
public class MaskPlaneAdjuster : Editor
{
    [MenuItem("Tools/LightMask/调整遮罩平面设置")]
    public static void AdjustMaskPlane()
    {
        // 查找场景中的LightMaskSystem
        LightMaskSystem lms = Object.FindObjectOfType<LightMaskSystem>();
        
        if (lms == null)
        {
            EditorUtility.DisplayDialog("错误", "场景中没有找到LightMaskSystem组件", "确定");
            return;
        }

        // 通过反射获取私有字段
        var maskPlaneField = typeof(LightMaskSystem).GetField("maskPlane", 
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var maskOffsetField = typeof(LightMaskSystem).GetField("maskOffset",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var planeSizeField = typeof(LightMaskSystem).GetField("planeSize",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

        Transform maskPlane = (Transform)maskPlaneField.GetValue(lms);
        Vector3 maskOffset = (Vector3)maskOffsetField.GetValue(lms);
        float planeSize = (float)planeSizeField.GetValue(lms);

        string info = $"当前遮罩平面设置:\n\n";
        info += $"遮罩平面物体: {(maskPlane != null ? maskPlane.name : "未设置")}\n";
        info += $"遮罩偏移: {maskOffset}\n";
        info += $"平面大小: {planeSize}\n\n";
        
        info += "建议设置:\n";
        info += "1. 遮罩平面Y坐标应该 >= 10（在所有Sprite之上）\n";
        info += "2. 平面大小应该 >= 100（覆盖整个可视区域）\n";
        info += "3. 遮罩平面的SortingOrder应该 = 9999（最大）";

        EditorUtility.DisplayDialog("遮罩平面信息", info, "确定");
        Debug.Log(info);
    }

    [MenuItem("Tools/LightMask/设置遮罩平面SortingOrder")]
    public static void SetMaskPlaneSortingOrder()
    {
        LightMaskSystem lms = Object.FindObjectOfType<LightMaskSystem>();
        
        if (lms == null)
        {
            EditorUtility.DisplayDialog("错误", "场景中没有找到LightMaskSystem组件", "确定");
            return;
        }

        var maskPlaneField = typeof(LightMaskSystem).GetField("maskPlane", 
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        Transform maskPlane = (Transform)maskPlaneField.GetValue(lms);

        if (maskPlane == null)
        {
            EditorUtility.DisplayDialog("错误", "LightMaskSystem中没有设置遮罩平面", "确定");
            return;
        }

        // 设置SortingOrder
        SpriteRenderer sr = maskPlane.GetComponent<SpriteRenderer>();
        if (sr == null)
        {
            EditorUtility.DisplayDialog("错误", $"遮罩平面 {maskPlane.name} 没有SpriteRenderer组件", "确定");
            return;
        }

        sr.sortingOrder = 9999;
        EditorUtility.SetDirty(maskPlane.gameObject);
        
        EditorUtility.DisplayDialog("完成", $"已设置 {maskPlane.name} 的SortingOrder为9999", "确定");
        Debug.Log($"✓ 已设置 {maskPlane.name} 的SortingOrder为9999");
    }
}
