#include "board.h"

#include <string.h>

void board_copy(Board *dst, const Board *src) {
    memcpy(dst, src, sizeof(Board));
}

int board_compute_pairs(const Board *b) {
    const int size = b->size;
    int pairs = 0;
    for (int y = 0; y < size; ++y) {
        for (int x = 0; x < size; ++x) {
            const uint8_t v = b->cells[y][x];
            if (x + 1 < size && b->cells[y][x + 1] == v) {
                pairs++;
            }
            if (y + 1 < size && b->cells[y + 1][x] == v) {
                pairs++;
            }
        }
    }
    return pairs;
}

int board_max_pairs(const Board *b) {
    return (b->size * b->size) / 2;
}

void board_apply_move(Board *b, const Move *m) {
    const int n = m->n;
    const int x0 = m->x;
    const int y0 = m->y;
    uint8_t temp[MAX_SIZE][MAX_SIZE];

    for (int dy = 0; dy < n; ++dy) {
        memcpy(temp[dy], &b->cells[y0 + dy][x0], (size_t)n);
    }

    for (int dy = 0; dy < n; ++dy) {
        for (int dx = 0; dx < n; ++dx) {
            /* clockwise rotation */
            b->cells[y0 + dy][x0 + dx] = temp[n - 1 - dx][dy];
        }
    }

    b->pair_count = board_compute_pairs(b);
}
