using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
#endif
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Giant.Res {

    public class BundleSceneRequest : AssetRequest
    {
        public readonly LoadSceneMode loadSceneMode;
        public readonly string sceneName;
        public string assetBundleName;
        protected BundleRequest bundle;

        public BundleSceneRequest(string _path, bool addictive) {
            path = _path;
            AssetsMgr.GetAssetBundleName(path, out assetBundleName);
            sceneName = Path.GetFileNameWithoutExtension(path);
            loadSceneMode = addictive ? LoadSceneMode.Additive : LoadSceneMode.Single;
        }

        internal override void Load()
        {
            if (!string.IsNullOrEmpty(assetBundleName)) {
                bundle = AssetsMgr.LoadBundle(assetBundleName);
                if (bundle != null)
                    //SceneManager.LoadScene(sceneName, loadSceneMode);
                    LoadScene();
                else
                {
                    try
                    {
                        LoadScene();
                        //SceneManager.LoadScene(sceneName, loadSceneMode);
                        loadState = LoadState.LoadAsset;
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                        loadState = LoadState.Loaded;
                    }
                }
            }
        }

        internal override void Unload()
        {
            if (bundle != null) {
                bundle.Release();
            }

            if (loadSceneMode == LoadSceneMode.Additive) {
                if (SceneManager.GetSceneByName(sceneName).isLoaded) {
                    SceneManager.UnloadSceneAsync(sceneName);
                }
            }
            bundle = null;
        }

        private void LoadScene() {
            if (AssetsMgr.UseAssetBundle)
            {
                SceneManager.LoadScene(sceneName, loadSceneMode);
            }
            else
            {
#if UNITY_EDITOR
                EditorSceneManager.LoadSceneInPlayMode(path, new LoadSceneParameters(loadSceneMode) );
#endif
            }
        }
    }
}

