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

[System.Serializable]
public struct TileData
{
    public PlayerTypes playerType;
    public Transform playerFinishingTileParent;
}

public class TilesManager : MonoBehaviour, IBootLoader, IDataLoader, IBase
{
    [SerializeField] private Tile[] generalTiles;
    [SerializeField] private TileData[] tileDatas;

    private GameplayManager gameplayManager;

    private Dictionary<PlayerTypes, List<Transform>> finishingTileDataPairs = new Dictionary<PlayerTypes, List<Transform>>();

    public void Initialize()
    {
        InterfaceManager.Instance.RegisterInterface<TilesManager>(this);
    }

    public void InitializeData()
    {
        gameplayManager = InterfaceManager.Instance.GetInterfaceInstance<GameplayManager>();

        foreach (var tileData in tileDatas)
        {
            if (gameplayManager.PlayerTypesCollection.Contains(tileData.playerType))
            {
                finishingTileDataPairs.Add(tileData.playerType, new List<Transform>());     
                foreach (Transform child in tileData.playerFinishingTileParent)
                    finishingTileDataPairs[tileData.playerType].Add(child);
            }
        }

        foreach (var tile in generalTiles)
        {
            tile.Init(gameplayManager.PlayerTypesCollection.Count);
        }
    }

    public int GetFinishingTileDataLength(PlayerTypes playerType) => finishingTileDataPairs[playerType].Count;

    public int GetGeneralTilesLength() => generalTiles.Length;

    public Tile RetrieveTileBasedOnIndex(int index)
    {
        Debug.Log($"RetrieveTileBasedOnIndex: Index: {index}");
        return index == generalTiles.Length ? generalTiles[0] : generalTiles[index];
    }

    public Transform RetrievePositionForFinishingTile(PlayerTypes playerType, int index)
    {
        return finishingTileDataPairs[playerType][index];
    }
}
