using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;
using System.Collections.Generic;
using System.Linq;

#if UNITY_EDITOR
public class BuildSettingsUpdater
{
    [UnityEditor.MenuItem("Tools/Update Build Settings with Waiting Scene")]
    public static void AddWaitingSceneToBuild()
    {
        // Get current scenes in build settings
        List<EditorBuildSettingsScene> scenes = new List<EditorBuildSettingsScene>(EditorBuildSettings.scenes);
        
        // Path to the waiting scene
        string waitingScenePath = "Assets/Scenes/WaitingScene.unity";
        
        // Check if the waiting scene exists in the project
        if (!System.IO.File.Exists(waitingScenePath))
        {
            Debug.LogError("WaitingScene.unity does not exist. Please create it first using Tools/Create Waiting Scene.");
            return;
        }
        
        // Check if the waiting scene is already in build settings
        bool alreadyInBuild = scenes.Any(scene => scene.path == waitingScenePath);
        
        if (!alreadyInBuild)
        {
            // Add the waiting scene right after the MenuScene (position 1)
            int menuSceneIndex = -1;
            for (int i = 0; i < scenes.Count; i++)
            {
                if (scenes[i].path.Contains("MenuScene"))
                {
                    menuSceneIndex = i;
                    break;
                }
            }
            
            if (menuSceneIndex >= 0)
            {
                scenes.Insert(menuSceneIndex + 1, new EditorBuildSettingsScene(waitingScenePath, true));
            }
            else
            {
                // If MenuScene not found, add it before Game scene
                int gameSceneIndex = -1;
                for (int i = 0; i < scenes.Count; i++)
                {
                    if (scenes[i].path.Contains("Game"))
                    {
                        gameSceneIndex = i;
                        break;
                    }
                }
                
                if (gameSceneIndex >= 0)
                {
                    scenes.Insert(gameSceneIndex, new EditorBuildSettingsScene(waitingScenePath, true));
                }
                else
                {
                    // If no Game scene found, add to the end
                    scenes.Add(new EditorBuildSettingsScene(waitingScenePath, true));
                }
            }
            
            // Save changes
            EditorBuildSettings.scenes = scenes.ToArray();
            
            Debug.Log("WaitingScene added to build settings.");
        }
        else
        {
            Debug.Log("WaitingScene is already in build settings.");
        }
    }
}
#endif 