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

const Grid = @import("grid.zig");
const Piece = @import("piece.zig");
const Bag = @import("bag.zig");

const preview = @import("preview.zig");
const movement = @import("movement.zig");

const Self = @This();

grid: Grid,
grid_cell_size: i32,
grid_pos_x: i32,
grid_pos_y: i32,

bag: Bag,

held: ?Piece,
piece: ?Piece,
renderer: *SDL.SDL_Renderer,

right_action: bool = false,
left_action: bool = false,
down_action: bool = false,

pub fn init(renderer: *SDL.SDL_Renderer) Self {
    var ret = Self{
        .grid = Grid.init(),
        .grid_cell_size = 16,
        .grid_pos_x = 16,
        .grid_pos_y = 16,

        .bag = Bag.init(),
        .piece = undefined,
        .held = null,
        .renderer = renderer,
    };
    ret.piece = Piece.init(ret.bag.pop());
    return ret;
}
fn render(self: Self) void {
    self.grid.render(self.renderer, self.grid_cell_size, self.grid_pos_x, self.grid_pos_y);
    if (self.piece) |safe_piece| {
        safe_piece.render(self.renderer, self.grid_cell_size, self.grid_pos_x, self.grid_pos_y);
    }
    preview.render(self.renderer, self.bag, self.grid_cell_size, self.grid_pos_x + self.grid_cell_size * (Grid.ncolumns + 1), self.grid_pos_y);
}
pub fn tick(self: *Self) void {
    if (self.piece) |safe_piece| {
        //std.debug.print("Piece: Col: {} Row: {}\n", .{ safe_piece.col, safe_piece.row });
        //std.debug.print("Bag: {any}\n", .{self.bag.contents});

        var key_state = SDL.SDL_GetKeyboardState(null);

        // MOVEMENT

        if (key_state[SDL.SDL_SCANCODE_D] == 1 and !self.right_action) {
            self.right_action = true;
            self.piece = movement.moveRight(self.grid, safe_piece);
        }
        if (key_state[SDL.SDL_SCANCODE_D] == 0) {
            self.right_action = false;
        }
        if (key_state[SDL.SDL_SCANCODE_A] == 1 and !self.left_action) {
            self.left_action = true;
            self.piece = movement.moveLeft(self.grid, safe_piece);
        }
        if (key_state[SDL.SDL_SCANCODE_A] == 0) {
            self.left_action = false;
        }
        if (key_state[SDL.SDL_SCANCODE_S] == 1 and !self.down_action) {
            self.down_action = true;
            self.piece = movement.moveDown(self.grid, safe_piece);
        }
        if (key_state[SDL.SDL_SCANCODE_S] == 0) {
            self.down_action = false;
        }
    }

    // DROP

    if (self.piece) |safe_piece| {
        if (safe_piece.dropped) {
            self.grid = movement.drop(self.grid, safe_piece);
            self.piece = Piece.init(self.bag.pop());
        }
    }

    self.render();
}
