#include <SDL.h>

#include "drawing.h" // This file
#include "game.h" // Get paused state
#include "globals.h" // Size macros
#include "grid.h" // Get grid state
#include "main.h" // Get window

void clear_window() {
    SDL_Surface *surface = SDL_GetWindowSurface(window);

    Uint32 background = SDL_MapRGB(surface->format, 0x2E, 0x34, 0x40);

    SDL_FillRect(surface, NULL, background);
}

SDL_Surface* grid_lines_surface() {
    Uint32 rmask, gmask, bmask, amask;
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x000000ff;

    SDL_Surface *grid_lines = SDL_CreateRGBSurface(0, WINDOW_WIDTH, WINDOW_HEIGHT, 32, rmask, gmask, bmask, amask);

    Uint32 lines_color = SDL_MapRGB(grid_lines->format, 0x3B, 0x42, 0x52);

    SDL_Surface *vertical = SDL_CreateRGBSurface(0, 2, WINDOW_HEIGHT, 32, rmask, gmask, bmask, amask);
    SDL_FillRect(vertical, NULL, lines_color);
    for (int i = 0; i <= GRID_WIDTH; i++) {
        SDL_Rect destination;
        destination.x = i * CELL_SIZE - 1;
        destination.y = 0;

        SDL_BlitSurface(vertical, NULL, grid_lines, &destination);
    } 
    SDL_FreeSurface(vertical);

    SDL_Surface *horizontal = SDL_CreateRGBSurface(0, WINDOW_WIDTH, 2, 32, rmask, gmask, bmask, amask);
    SDL_FillRect(horizontal, NULL, lines_color);
    for (int i = 0; i <= GRID_HEIGHT; i++) {
        SDL_Rect destination;
        destination.x = 0;
        destination.y = i * CELL_SIZE - 1;

        SDL_BlitSurface(horizontal, NULL, grid_lines, &destination);
    } 
    SDL_FreeSurface(horizontal);

    return grid_lines;
}

SDL_Surface* cell_surface() {
    SDL_Surface *cell = SDL_CreateRGBSurface(0, CELL_SIZE, CELL_SIZE, 32, 0, 0, 0, 0);

    Uint32 cell_color = SDL_MapRGB(cell->format, 0xE5, 0xE9, 0xF0);
    SDL_FillRect(cell, NULL, cell_color);

    return cell;
}

void draw() {
    clear_window();

    draw_cells();

    if (paused) draw_grid_lines();

    SDL_UpdateWindowSurface(window);
}

void draw_grid_lines() {
    SDL_Surface *surface = SDL_GetWindowSurface(window);
    static SDL_Surface *grid_lines = grid_lines_surface();

    SDL_BlitSurface(grid_lines, NULL, surface, &surface->clip_rect);
}

void draw_cells() {
    SDL_Surface *surface = SDL_GetWindowSurface(window);
    static SDL_Surface *cell = cell_surface();

    for (int i = 0; i < GRID_HEIGHT; i++)
        for (int j = 0; j < GRID_WIDTH; j++) {
            if (grid[i][j] == ALIVE) {
                SDL_Rect destination;
                destination.x = j * CELL_SIZE;
                destination.y = i * CELL_SIZE;

                SDL_BlitSurface(cell, NULL, surface, &destination);
            }
        }
}