const std = @import("std");
const SDL = @import("sdl2");

const Color = @import("color.zig");
const Cell = @import("cell.zig");
const utils = @import("utils.zig");

const range = utils.range;

const Self = @This();

pub const ncolumns = 10;
pub const nrows = 30;
pub const buffer = 10;

cells: [nrows][ncolumns]Cell,
topped: bool = false,

pub fn init() Self {
    var self = Self{
        .cells = undefined,
    };

    for (self.cells) |_, i| {
        for (self.cells[i]) |_, j| {
            self.cells[i][j] = Cell.init();
        }
    }

    return self;
}

pub fn clearLines(self: *Self) void {
    for (self.cells) |_, y| {
        for (self.cells[y]) |cell_x, x| {
            if (cell_x.free) {
                break;
            } else {
                // Reached the end of the column?
                if (x == self.cells[y].len - 1) {
                    // Delete current row and bring the others down
                    for (self.cells[1..y]) |_, i| {
                        self.cells[y - i] = self.cells[y - i - 1];
                    }
                }
            }
        }

    }


}

pub fn render(self: Self, renderer: *SDL.SDL_Renderer, cell_size: i32, pos_x: i32, pos_y: i32) void {
    var rect = SDL.SDL_Rect{
        .x = pos_x,
        .y = pos_y,
        .w = cell_size,
        .h = cell_size,
    };

    var visible = self.cells[buffer..];
    for (visible) |_, y| {
        for (visible[y]) |_, x| {
            var r = visible[y][x].color.r;
            var g = visible[y][x].color.g;
            var b = visible[y][x].color.b;
            var a = visible[y][x].color.a;

            rect.x = pos_x + @intCast(i32, x) * cell_size;
            rect.y = pos_y + (@intCast(i32, y) + buffer) * cell_size;

            _ = SDL.SDL_SetRenderDrawColor(renderer, r, g, b, a);
            _ = SDL.SDL_RenderFillRect(renderer, &rect);
            _ = SDL.SDL_SetRenderDrawColor(renderer, Color.light_grey.r, Color.light_grey.g, Color.light_grey.b, Color.light_grey.a);
            _ = SDL.SDL_RenderDrawRect(renderer, &rect);
        }
    }
}
