using Godot;
using System;

public partial class GameBoard : TextureRect
{
    private const int SLOT_TEXTURE_SIZE = 230;

    private bool isEnabled;
    private int[][] slots;
    private Action<int, int> slotClickAction;

    public Action<int, int> SlotClickAction
    {
        get => slotClickAction;
        set => slotClickAction = value;
    }

    public void Init()
    {
        // We use a two-dimensional array with 4x4 entries, so we can have 1-based indexes for the board
        slots = [
            new int[4],
            new int[4],
            new int[4],
            new int[4],
        ];

        // Load atlas texture
        Texture2D atlasTexture = GD.Load<Texture2D>("res://images/game/marks.png");

        for (int r = 1; r <= 3; r++)
        {
            for (int c = 1; c <= 3; c++)
            {
                TextureButton slot = GetSlot(r, c);

                // Assign independent texture
                AtlasTexture texture = new()
                {
                    Atlas = atlasTexture,
                    Region = new Rect2(0, 0, SLOT_TEXTURE_SIZE, SLOT_TEXTURE_SIZE) // First image region
                };

                // Add random flip
                slot.FlipH = new Random().Next(2) == 1;
                slot.FlipV = new Random().Next(2) == 1;

                // Assign the independent atlas texture
                slot.TextureNormal = texture;

                // Set press listener
                int row = r;
                int col = c;
                slot.Pressed += () => {
                    if (isEnabled)
                        slotClickAction?.Invoke(row, col);
                };
            }
        }
    }

    public bool IsEnabled
    {
        get => isEnabled;
        set => isEnabled = value;
    }

    public void Reset()
    {
        for (int r = 1; r <= 3; r++)
            for (int c = 1; c <= 3; c++)
                SetMark(r, c, 0);
    }

    public void SetMark(int r, int c, int value)
    {
        AtlasTexture texture = (AtlasTexture)GetSlot(r, c).TextureNormal;
        texture.Region = new Rect2(value * SLOT_TEXTURE_SIZE, 0, SLOT_TEXTURE_SIZE, SLOT_TEXTURE_SIZE);

        // Rect2 region = texture.Region;
        // Vector2 position = region.Position;
        // Vector2 size = region.Position;
        // position.X = value * SLOT_TEXTURE_SIZE;

        // region.Position = position;
        // region.Size = size;
        // texture.Region = region;
    }

    private TextureButton GetSlot(int r, int c)
    {
        string slotName = String.Format("Slot{0}{1}", r, c);
        return (TextureButton)this.FindChild(slotName);
    }
}
