using System;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class GridManager : MonoBehaviour
{
    [SerializeField] private Vector2Int GridSize;
    [SerializeField] private float Gap = 0.1f;
    [SerializeField] private GridType gridType = GridType.Primary;
    [Space(10)]
    [SerializeField] private GameObject TowerSlotPrefab;

    [DoNotSerialize] public List<GameObject> SpawnedSlots = new();

    [DoNotSerialize] public string[,] GridStates;

    private void OnEnable()
    {
        TowerPlacementManager.OnSpawnGridRequested += SpawnSlots;

        GridStates = new string[GridSize.x, GridSize.y];
    }

    private void OnDisable()
    {
        TowerPlacementManager.OnSpawnGridRequested -= SpawnSlots;
    }

    public void SpawnSlots(TowerPlacementManager sender)
    {
        for (int x = 0; x < GridSize.x; x++)
        {
            for (int y = 0; y < GridSize.y; y++)
            {
                // Spawn slot
                Vector3 spawnPosition = new(x * (Gap + 1) + 0.5f, 0, y * (Gap + 1) + 0.5f);
                var spawned = Instantiate(TowerSlotPrefab, transform);
                spawned.transform.localPosition = spawnPosition;

                // Give the slot a ref
                var infoHolder = spawned.GetComponent<SlotManager>();
                infoHolder.spawnerRef = this;
                infoHolder.x = x;
                infoHolder.y = y;

                infoHolder.OnSlotClicked += sender.OnSlotClicked;

                SpawnedSlots.Add(spawned);
            }
        }
    }
}

public enum GridType
{
    Primary,
    Wall,
    Celling
}