using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.XR.ARFoundation;

namespace XenseAR
{
    public class ARSupportChecker : MonoBehaviour
    {
        // Start is called before the first frame update
        IEnumerator Start()
        {
#if true
            bool isARInitialized = false;
            yield return StartCoroutine(StartChecking((status) => isARInitialized = status));

            if (!isARInitialized)
            {
                if(!SceneManager.GetActiveScene().name.Equals("MegaTracking"))
                {
                    PopupDialog.instance.showButtonDialog(PopupDialog.DialogTemplate.Notification,
                        XenseARDictionary.Instance.GetLocalizationText(Defines.LocalizationKey.arNotSupport), "OK",
                    () =>
                    {
                        //Exit the scene
                        StartCoroutine(LoadHomeScene());
                    }, Defines.Theme.ThemeColor, Defines.Theme.ThemeBoldTextColor);
                } else
                {
                    //Mega Tracking does not use ARFoundation.
                }
                yield break;
            }
#endif
        }

        IEnumerator LoadHomeScene()
        {
#if USE_VUPLEX_WEBVIEW
            ARWorldWebview.Instance.BackToPreviousPage();
            ARWorldWebview.Instance.Open();
#endif
            API.BackToHomeScreen("");

            string currentScene = SceneManager.GetActiveScene().name;
            Scene previousScene = SceneManager.GetSceneByName("StartScene");
            if (previousScene.IsValid())
            {
                GameObject[] rootObjects = previousScene.GetRootGameObjects();
                foreach (GameObject rootObject in rootObjects)
                {
                    rootObject.SetActive(true);
                }
            }


            var operation = SceneManager.UnloadSceneAsync(currentScene, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects);
            operation.completed += (asyncOperation) =>
            {
                Resources.UnloadUnusedAssets();
            };
            yield return null;
        }

        public static IEnumerator StartChecking(System.Action<bool> OnStatusReceived)
        {
            while (true)
            {
                switch (ARSession.state)
                {
                    case ARSessionState.None:
                    case ARSessionState.CheckingAvailability:
                        yield return ARSession.CheckAvailability();
                        continue;
                    case ARSessionState.NeedsInstall:
                        yield return ARSession.Install();
                        continue;
                    case ARSessionState.Unsupported:
                        OnStatusReceived?.Invoke(false);
                        yield break;
                    case ARSessionState.Ready:
                    case ARSessionState.SessionTracking:
                        OnStatusReceived?.Invoke(true);
                        yield break;
                    case ARSessionState.Installing:
                    case ARSessionState.SessionInitializing:
                        yield return null;
                        continue;
                }
            }
        }
    }
}

