using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace MajacloudSdk.Samples.Starter
{
    /// <summary>Button that opens another demo scene. Works from Build Settings, or straight from the project in the editor.</summary>
    [RequireComponent(typeof(Button))]
    public sealed class SceneLink : MonoBehaviour
    {
        [SerializeField] private string scenePath;

        private void Awake() => GetComponent<Button>().onClick.AddListener(Open);

        public void Open() => Load(scenePath);

        public static void Load(string path)
        {
            if (string.IsNullOrEmpty(path)) return;
            if (SceneUtility.GetBuildIndexByScenePath(path) >= 0)
            {
                SceneManager.LoadScene(path);
                return;
            }
            // The sample may have been moved (e.g. imported through Package Manager): match by file name.
            var fileName = Path.GetFileNameWithoutExtension(path);
            for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
            {
                var candidate = SceneUtility.GetScenePathByBuildIndex(i);
                if (Path.GetFileNameWithoutExtension(candidate) != fileName) continue;
                SceneManager.LoadScene(i);
                return;
            }
#if UNITY_EDITOR
            var editorPath = File.Exists(path) ? path : FindInProject(fileName);
            if (editorPath != null)
            {
                UnityEditor.SceneManagement.EditorSceneManager.LoadSceneInPlayMode(editorPath, new LoadSceneParameters(LoadSceneMode.Single));
                return;
            }
#endif
            Debug.LogWarning("[Majacloud Demo] Scene \"" + fileName + "\" is not in Build Settings. Run Tools › Majacloud › Rebuild Starter Sample.");
        }

#if UNITY_EDITOR
        private static string FindInProject(string fileName)
        {
            foreach (var guid in UnityEditor.AssetDatabase.FindAssets("t:Scene " + fileName))
            {
                var candidate = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
                if (Path.GetFileNameWithoutExtension(candidate) == fileName) return candidate;
            }
            return null;
        }
#endif
    }
}
