#nullable enable
using System.Collections.Generic;
using Godot;

namespace AceFieldNewHorizon.Scripts.System;

public partial class GridManager : Node
{
    private Dictionary<Vector2I, Node2D> _grid = new();

    public bool IsCellFree(Vector2I cell)
    {
        return !_grid.ContainsKey(cell);
    }

    public void OccupyCell(Vector2I cell, Node2D building)
    {
        _grid[cell] = building;
    }

    public void FreeCell(Vector2I cell)
    {
        _grid.Remove(cell);
    }

    public Node2D? GetBuildingAtCell(Vector2I cell)
    {
        return _grid.GetValueOrDefault(cell);
    }
}

public static class GridUtils
{
    public const int TileSize = 54;

    public static Vector2I WorldToGrid(Vector2 pos)
    {
        return new Vector2I(
            Mathf.FloorToInt(pos.X / TileSize),
            Mathf.FloorToInt(pos.Y / TileSize)
        );
    }

    public static Vector2 GridToWorld(Vector2I cell)
    {
        return new Vector2(
            cell.X * TileSize,
            cell.Y * TileSize
        );
    }
}