using System.Threading.Tasks;
using UnityEngine;

namespace SC.XR.Unity
{

    public class ProgressIndicatorController : MonoBehaviour
    {
        [SerializeField, Header("Indicators")]
        protected GameObject progressIndicatorLoadingBarGo = null;
        [SerializeField]
        protected GameObject progressIndicatorLoadingOrbGo = null;
        [SerializeField, Range(0f, 1f)]
        public float targetProgress = 0f;

        protected IProgressIndicator progressIndicatorLoadingBar;
        protected IProgressIndicator progressIndicatorLoadingOrb;
        private void OnEnable()
        {
            progressIndicatorLoadingBar = progressIndicatorLoadingBarGo.GetComponent<IProgressIndicator>();
            progressIndicatorLoadingOrb = progressIndicatorLoadingOrbGo.GetComponent<IProgressIndicator>();
        }
        public void Update()
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                HandleButtonClick(progressIndicatorLoadingBar);
                HandleButtonClick(progressIndicatorLoadingOrb);
            }
            progressIndicatorLoadingBar.SetProgress(targetProgress);
            progressIndicatorLoadingOrb.SetProgress(targetProgress);
        }

        protected async void HandleButtonClick(IProgressIndicator indicator)
        {
            // If the indicator is opening or closing, wait for that to finish before trying to open / close it
            // Otherwise the indicator will display an error and take no action

            await indicator.AwaitTransitionAsync();
            switch (indicator.State)
            {
                case ProgressIndicatorState.Closed:
                    await indicator.OpenAsync();
                    break;

                case ProgressIndicatorState.Open:
                    await indicator.CloseAsync();
                    break;
            }
        }


        //private async void OpenProgressIndicator(IProgressIndicator indicator)
        //{
        //    await indicator.OpenAsync();

        //    float timeStarted = Time.time;
        //    while (Time.time < timeStarted + loadingTime)
        //    {
        //        float normalizedProgress = Mathf.Clamp01((Time.time - timeStarted) / loadingTime);
        //        indicator.Progress = normalizedProgress;


        //        await Task.Yield();

        //        switch (indicator.State)
        //        {
        //            case ProgressIndicatorState.Open:
        //                break;

        //            default:
        //                // The indicator was closed
        //                return;
        //        }
        //    }

        //    await indicator.CloseAsync();
        //}

    }
}