#include "Board.h"
#include <algorithm>

namespace logic {

Board::Board()
    : grid_(Width * Height, Cell::Empty)
{
}

void Board::clear()
{
    std::fill(grid_.begin(), grid_.end(), Cell::Empty);
}

bool Board::inBounds(int x, int y) const
{
    return x >= 0 && x < Width && y >= 0 && y < Height;
}

Board::Cell Board::at(int x, int y) const
{
    if (!inBounds(x, y)) return Cell::Empty;
    return grid_[y * Width + x];
}

void Board::set(int x, int y, Cell c)
{
    if (!inBounds(x, y)) return;
    grid_[y * Width + x] = c;
}

int Board::clearFullLines()
{
    int cleared = 0;
    // scan from bottom to top
    for (int y = Height - 1; y >= 0; --y) {
        bool full = true;
        for (int x = 0; x < Width; ++x) {
            if (at(x, y) == Cell::Empty) { full = false; break; }
        }
        if (full) {
            // remove row y: move all rows above down by one
            for (int yy = y; yy > 0; --yy) {
                for (int x = 0; x < Width; ++x) {
                    grid_[yy * Width + x] = grid_[(yy - 1) * Width + x];
                }
            }
            // clear top row
            for (int x = 0; x < Width; ++x) grid_[x] = Cell::Empty;
            ++cleared;
            // stay on same y to re-check the row that fell into place
            ++y; // because next iteration decrements y
        }
    }
    return cleared;
}

} // namespace logic
