using System.Linq;
using System.Collections.Generic;
using UDB;
using UDB.UI;
using UnityEngine;
using UnityEngine.Events;
using Eflatun.SceneReference;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class SceneLoaderHelper : MonoBehaviour
{
    [SerializeField]
    private SceneReference scene;

    [SerializeField]
    private SceneLoaderCoordinator sceneLoaderCoordinator;

    public UnityEvent OnLoaded;

    public bool useNetworkSceneDirector = true;


#if UNITY_EDITOR
    void OnValidate()
    {
        if(sceneLoaderCoordinator == null) {
            List<SceneLoaderCoordinator> sceneLoaderCoordinators = AssetDatabase.FindAssets($"t: {typeof(SceneLoaderCoordinator).Name}").ToList()
                 .Select(AssetDatabase.GUIDToAssetPath)
                 .Select(AssetDatabase.LoadAssetAtPath<SceneLoaderCoordinator>)
                 .ToList();
            sceneLoaderCoordinator = sceneLoaderCoordinators.First();
        }
    }
#endif

    public void Play()
    {
        string sceneName = scene.Name;
        if (useNetworkSceneDirector) {
            NetworkSceneDirector.instance.LoadSingleScene(sceneName, () => {
                OnLoaded.Invoke();
            });
        } else {
            sceneLoaderCoordinator.LoadScene(sceneName, () => {
                OnLoaded.Invoke();
            });
        }
    }
}
