using System;
using System.Collections.Generic;
using Core.Domain;
using UnityEngine;

namespace Infrastructure.Unity
{
    public class TileRegistry
    {
        private readonly List<Tile> _tiles = new();
        private readonly Dictionary<string, TileViewAdapter> _views = new();

        public IReadOnlyList<Tile> AllTiles => _tiles;

        public void Register(Tile tile, TileViewAdapter view = null)
        {
            _tiles.Add(tile);
            if (view != null) _views[tile.Id] = view;
        }

        public bool TryGetView(string tileId, out TileViewAdapter view)
            => _views.TryGetValue(tileId, out view);

        public List<Tile> FindTiles(Predicate<Tile> predicate)
            => _tiles.FindAll(predicate);

        public List<List<TileViewAdapter>> GroupViewsByFloor(int floorCount)
        {
            var floors = new List<List<TileViewAdapter>>(floorCount);
            for (var i = 0; i < floorCount; i++) floors.Add(new List<TileViewAdapter>());

            foreach (var tile in _tiles)
            {
                if (tile.Floor >= floorCount)
                {
                    Debug.LogWarning($"TileRegistry: tile '{tile.Id}' floor {tile.Floor} >= floorCount {floorCount}, skipping");
                    continue;
                }
                if (_views.TryGetValue(tile.Id, out var view))
                    floors[tile.Floor].Add(view);
            }

            return floors;
        }
    }
}
