using RebootKit.Engine.Foundation;
using RebootKit.Engine.Simulation;
using UnityEditor;
using UnityEngine;

namespace RebootKit.Editor.Background {
    [InitializeOnLoad]
    public class EnsureUniqueActorID {
        static EnsureUniqueActorID() {
            ObjectChangeEvents.changesPublished += OnObjectChange;
        }

        static void OnObjectChange(ref ObjectChangeEventStream stream) {

            for (int i = 0; i < stream.length; ++i) {
                switch (stream.GetEventType(i)) {
                    case ObjectChangeKind.CreateGameObjectHierarchy:
                        stream.GetCreateGameObjectHierarchyEvent(i, out CreateGameObjectHierarchyEventArgs createEvent);

                        GameObject gameObjectChanged =
                            EditorUtility.InstanceIDToObject(createEvent.instanceId) as GameObject;

                        if (gameObjectChanged != null && gameObjectChanged.TryGetComponent(out Actor actor)) {
                            actor.ActorStaticID = UniqueID.NewULongFromGuid();
                            EditorUtility.SetDirty(actor);
                        }

                        break;
                }
            }
            
        }
    }
}