using Assets.Source.Content.UI.Topdown;
using Assets.Source.Patterns;
using Assets.Source.UI;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Assets.Source.Core.Gameplay.Topdown
{
    public class GameManagerTopdown : Singleton<GameManagerTopdown>
    {
        public BoxCollider2D Bounds;
        public PlayerShipTopdown Player;
        public PlayerInventory PlayerInventory;
        public WorldMapSpawner WorldMap;
        public bool SolvingPlanet;

        public bool InputEnabled
            => Get.MainUI.DialogueLayer.Get<UITopdownInventoryDialogue>().State != UIElementState.Opened &&
               Get.MainUI.DialogueLayer.Get<UIDefeatDialogue>().State != UIElementState.Opened &&
            Get.MainUI.DialogueLayer.Get<UIVideoDialogue>("Start").State != UIElementState.Opened &&
            Get.MainUI.DialogueLayer.Get<UIVideoDialogue>("Final").State != UIElementState.Opened;

        protected override void Init()
        {
            base.Init();

            FindInstances();
            WorldMap.SpawnWorld();
        }

        protected override void HandleLoadedLevel(Scene scene, LoadSceneMode mode)
        {
            base.HandleLoadedLevel(scene, mode);
            FindInstances();
            Get.MainUI.DialogueLayer.Get<UIVideoDialogue>("Start").Open();
        }

        private void FindInstances()
        {
            Player = FindObjectOfType<PlayerShipTopdown>();
            Bounds = GameObject.Find("_WorldBounds").GetComponent<BoxCollider2D>();
            WorldMap = FindObjectOfType<WorldMapSpawner>();
        }

        public void SpawnScenarioCharacter()
        {
            var c = Get.CommonPrefabs.TopdownPrefabs.ScenarioCharacter.Spawn(WorldMap.AlienAreas.GetRandom().bounds.center);
            c.InitPerks(null);
            c.OnTakeSeat += () =>
            {
                var inv = Get.MainUI.DialogueLayer.Get<UITopdownInventoryDialogue>();
                inv.ScenarioCharacterImage.gameObject.SetActive(true);
                inv.ScenarioItemImage.gameObject.SetActive(true);
                var video = Get.MainUI.DialogueLayer.Get<UIVideoDialogue>("Final");//.Open();
                video.Open();
                video.OnNextCloseEnd += () => Get.MainUI.DialogueLayer.Open<UITopdownInventoryDialogue>();
            };
            Player.SetNextDestination(c.transform);
        }
    }
}
