using System;
using System.Collections.Generic;
using UnityEngine;
using DefaultNamespace.ProcessMode;
using Framework.Dto;
using MotionFramework;

public static class EventRegistrationCenter
{
    private static Action onAllEventsRegistered; // 注册所有事件后的回调，用于跳转步骤

    // 存储所有步骤的事件信息
    private static List<EventStepInfo> allStepEvents = new List<EventStepInfo>();

    /// <summary>
    /// 使用下标注册目标事件
    /// </summary>
    public static void RegisterEvent(
        int stepIndex,
        int actionIndex,
        string objectName,
        Action customEvent
        ) // 注册事件完成后的回调
    {
        // 场景已加载，直接注册
        InternalRegisterEvent(stepIndex, actionIndex, objectName, customEvent);
    }

    private static void InternalRegisterEvent(
        int stepIndex,
        int actionIndex,
        string objectName,
        Action customEvent)
    {
        var processManager = MotionEngine.GetModule<ProcessManager>();
        var processCollection = processManager.CurrentProcessCollection;

        // 检查步骤索引和动作索引有效性
        if (stepIndex < 0 || stepIndex >= processCollection.Steps.Count)
        {
            Debug.LogError($"步骤索引 {stepIndex} 超出范围！");
            return;
        }

        var step = processCollection.Steps[stepIndex];

        if (actionIndex < 0 || actionIndex >= step.Actions.Count)
        {
            Debug.LogError($"动作索引 {actionIndex} 超出范围！");
            return;
        }

        var action = step.Actions[actionIndex];
        action.BindEventToObject(objectName, customEvent); // 将事件绑定到目标物体
        Debug.Log($"事件绑定成功：步骤 {step.StepDescription} -> 动作 {action.Title} -> {objectName}");

    }


    /// <summary>
    /// 添加事件到 AllStepEvents
    /// </summary>
    public static void AddEventsToAllStepEvents(EventStepInfo eventStep)
    {
        if (allStepEvents != null)
        {
            allStepEvents.Add(eventStep);
            Debug.Log($"事件已添加，当前事件总数: {allStepEvents.Count}");
        }
        else
        {
            Debug.LogError("AllStepEvents is not loaded.");
        }
    }

    /// <summary>
    /// 注册所有步骤的事件
    /// </summary>
    public static void RegisterAllEvents()
    {
        if (allStepEvents != null)
        {
            foreach (var stepEvent in allStepEvents)
            {
                RegisterEvent(
                    stepEvent.StepIndex,
                    stepEvent.ActionIndex,
                    stepEvent.ObjectName,
                    stepEvent.Event
                );
            }
        }
        else
        {
            Debug.LogError("AllStepEvents is not loaded.");
        }
    }
}
