using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Assets.Source.Core.Gameplay.Topdown
{
    public class WorldMapSpawner : MonoBehaviour
    {
        public Transform PlanetsRoot;
        public Transform AliensRoot;

        public List<BoxCollider2D> PlanetAreas;
        public List<BoxCollider2D> AlienAreas;

        public List<PlanetTopdown> Planets { get; } = new List<PlanetTopdown>();
        public List<AlienTopdown> Aliens { get; } = new List<AlienTopdown>();

        public void SpawnWorld()
        {
            PlanetAreas = PlanetsRoot.GetComponentsInChildren<BoxCollider2D>().ToList();
            AlienAreas = AliensRoot.GetComponentsInChildren<BoxCollider2D>().ToList();
            PlanetAreas.Shuffle();

            SpawnAliens();
            SpawnPlanets();
        }

        private void SpawnAliens()
        {
            int variation = 0;
            int atmoVariation = 0;
            foreach (var a in AlienAreas)
            {
                var info = new AlienInfo { Character = Get.MechanicSettings.Characters[variation] };
                var perksSetup = new Dictionary<PlanetPerk, bool>();
                perksSetup.Add(info.Character.NativeSurface, true);
                perksSetup.Add(Get.MechanicSettings.AtmospherePerks[atmoVariation], Random.value > 0.5);
                info.PerksSetup = perksSetup;

                var alien = Get.CommonPrefabs.TopdownPrefabs.Alien.Spawn(a.bounds.RandomPoint());
                Aliens.Add(alien);
                alien.transform.SetParent(AliensRoot);
                alien.InitPerks(info);

                variation++;
                atmoVariation++;
                if (atmoVariation >= Get.MechanicSettings.AtmospherePerks.Count)
                    atmoVariation = 0;
            }
        }

        private void SpawnPlanets()
        {
            for (int i = 0; i < Aliens.Count; i++)
            {
                var area = PlanetAreas[i];
                var planetPrefab =
                    Aliens[i].AlienInfo.PerksSetup.ToList()
                        .FirstOrDefault(pair => pair.Key.Type == PlanetPerkType.Surface)
                        .Key.Prefab;//Get.CommonPrefabs.TopdownPrefabs.Planet.Spawn(area.bounds.RandomPoint());
                var planet = planetPrefab.Spawn(area.bounds.RandomPoint());
                Planets.Add(planet);
                planet.transform.SetParent(PlanetsRoot);
                planet.InitFromPerks(Aliens[i].AlienInfo);
            }
        }
    }
}
