﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

using Arbor;

namespace ArborEditor
{
	[InitializeOnLoad]
	class UndoComponentInitializer
	{
		static void RefreshStateMachine(ArborFSMInternal stateMachine)
		{
			bool cachedEnabled = ComponentUtility.enabled;
			ComponentUtility.enabled = false;

			stateMachine.Refresh();

			ComponentUtility.enabled = cachedEnabled;
		}
		
		static List<Object> s_DelayDestroyObjects = new List<Object>();

		static bool s_DelayDestroyEnable = false;

		static void AddDelayDestroyObject(Object obj)
		{
			s_DelayDestroyObjects.Add(obj);

			if (!s_DelayDestroyEnable)
			{
				EditorApplication.delayCall += OnDelayDestroyObjects;
				s_DelayDestroyEnable = true;
			}
		}

		static void OnDelayDestroyObjects()
		{
			foreach (Object obj in s_DelayDestroyObjects)
			{
				ComponentUtility.Destroy(obj);
			}
			s_DelayDestroyObjects.Clear();

			s_DelayDestroyEnable = false;
		}
		
		static UndoComponentInitializer()
		{
			ComponentUtility.editorAddComponent = Undo.AddComponent;
			ComponentUtility.editorDestroyObjectImmediate = Undo.DestroyObjectImmediate;
			ComponentUtility.editorRecordObject = Undo.RecordObject;
			ComponentUtility.editorRecordObjects = Undo.RecordObjects;
			ComponentUtility.editorRegisterCompleteObjectUndo = Undo.RegisterCompleteObjectUndo;
			ComponentUtility.editorMoveBehaviour = EditorGUITools.MoveBehaviour;
			ComponentUtility.editorMoveCalculator = EditorGUITools.MoveCalculator;
            ComponentUtility.editorRefreshStateMachine = RefreshStateMachine;
			ComponentUtility.editorDelayDestroy = AddDelayDestroyObject;
			ComponentUtility.editorSetDirty = EditorUtility.SetDirty;
		}
	}
}
