#if UNITY_EDITOR
namespace NiAkaDev.EzMirror.Editor
{
    using UnityEditor;
    using UnityEditor.SceneManagement;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    using VRC.SDKBase.Editor.BuildPipeline;

    public class EzMirrorBuildProcessor : IVRCSDKBuildRequestedCallback
    {
        public int callbackOrder => 0;

        public bool OnBuildRequested(VRCSDKRequestedBuildType requestedBuildType)
        {
            if (requestedBuildType != VRCSDKRequestedBuildType.Scene)
                return true;

            Scene activeScene = SceneManager.GetActiveScene();
            if (!activeScene.IsValid())
                return true;

            bool changed = false;
            GameObject[] roots = activeScene.GetRootGameObjects();
            for (int rootIndex = 0; rootIndex < roots.Length; rootIndex++)
            {
                EzMirror[] mirrors = roots[rootIndex].GetComponentsInChildren<EzMirror>(true);
                for (int mirrorIndex = 0; mirrorIndex < mirrors.Length; mirrorIndex++)
                {
                    changed |= EzMirrorEditor.EnsureDedicatedGeneratedProfileMaterials(
                        mirrors[mirrorIndex]
                    );
                }
            }

            if (changed)
            {
                EditorSceneManager.MarkSceneDirty(activeScene);
                AssetDatabase.SaveAssets();
            }
            return true;
        }
    }
}
#endif
