using RothenburgAR.Updater;
using UnityEngine;

namespace RothenburgAR.UI
{
    public class UpdaterViewBehaviour : BaseViewBehaviour
    {
        public UnityEngine.UI.Slider ProgressBar;
        public GameObject UpdateDialog;
        public GameObject UpdateConfirmationDialog;
        public GameObject UpdateCompletedDialog;
        public GameObject UpdateFailedDialog;

        private UpdateState lastUpdateState = UpdateState.UpdatesFound;

        private void Start()
        {
            UpdateDialog.SetActive(true);
            UpdateConfirmationDialog.SetActive(false);
            UpdateCompletedDialog.SetActive(false);
            UpdateFailedDialog.SetActive(false);
            ProgressBar.value = 0;
            ProgressBar.maxValue = 1;
        }

        private void Update()
        {
            ProgressBar.value = UpdateManager.Instance.CurrentProgress;
            ProgressBar.maxValue = UpdateManager.Instance.MaxProgress;

            var state = UpdateManager.Instance.UpdateState;
            if (state == lastUpdateState) return;
            lastUpdateState = state;

            UpdateDialog.SetActive(false);
            UpdateConfirmationDialog.SetActive(false);
            UpdateCompletedDialog.SetActive(false);
            UpdateFailedDialog.SetActive(false);

            switch (state)
            {
                case UpdateState.ConfirmationPending:
                    UpdateConfirmationDialog.SetActive(true);
                    break;

                case UpdateState.UpdatesFound:
                case UpdateState.Downloading:
                    UpdateDialog.SetActive(true);

                    break;

                case UpdateState.Completed:
                    UpdateCompletedDialog.SetActive(true);
                    //TODO add "apply upgrades" button or sth that Destroys all DontDestroyOnLoads and reloads the scene, use AppInitializerBehaviour for that
                    break;

                case UpdateState.Failed:
                    UpdateFailedDialog.SetActive(true);
                    break;
            }
        }

        public void TriggerUpdate()
        {
            UpdateManager.Instance.TriggerUpdate();
        }

        public void ExitView()
        {
            UIManager.Instance.SwitchToView(ViewName.ARView);
        }

    }
}