using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;

namespace MenuMap
{
    public class OpenLevelPanel : PageAnimation
    {
        public static Action<int> ShowAndSetPanel;
        
        [SerializeField] private Button openLevelButton;
        private int _levelIndex;

        public void Start()
        {
            base.Start();
            ShowAndSetPanel += SetLevelIndex;
            openLevelButton.onClick.AddListener(() => StartCoroutine(OpenLevel()));
        }

        private void OnDestroy()
        {
            ShowAndSetPanel -= SetLevelIndex;
        }

        public void SetLevelIndex(int levelIndex)
        {
            _levelIndex = levelIndex;
            OpenPage();
        }

        private IEnumerator OpenLevel()
        {
            AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(_levelIndex);
            asyncLoad.allowSceneActivation = false;
            yield return new WaitForSeconds(0);
            asyncLoad.allowSceneActivation = true;
        }
        
        public override void ClosePageOnComplete()
        {
            MapCharacterController.BlockMovement?.Invoke(false);
        }
    }
}
