//
// Created by william on 7/12/24.
//

#ifndef NES_EMULATOR_DBG_PATTERN_TABLE_H
#define NES_EMULATOR_DBG_PATTERN_TABLE_H

#include <stdbool.h>
#include "../include/types.h"

#define PATTERN_BANK_SIZE 0x1000
#define PATTERN_TABLE_WIDTH 0x10
#define PATTERN_TABLE_SIZE (PATTERN_TABLE_WIDTH * PATTERN_TABLE_WIDTH)
#define PATTERN_SIZE 8
#define PATTERN_BYTES (PATTERN_SIZE * 2)
#define PATTERN_BORDER_WIDTH 1
#define PATTERN_BORDER_COLOR 0xff2223b2
#define PATTERN_DRAW_SIZE (PATTERN_SIZE + PATTERN_BORDER_WIDTH)

#define PATTERN_BANK_0 0
#define PATTERN_BANK_1 1

typedef unsigned int pixel;

typedef struct dbg_pattern {
    byte data_low[PATTERN_SIZE];
    byte data_high[PATTERN_SIZE];
} DebugPattern;

typedef struct dbg_pattern_table {
    DebugPattern bank_0[PATTERN_TABLE_SIZE];
    DebugPattern bank_1[PATTERN_TABLE_SIZE];
    bool initialized;
} DebugPatternTable;

/**
 * Initializes the debug pattern table. Build the two pattern banks from the currently loaded ROM.
 */
void dbg_pattern_table_init();

/**
 * Gets a debug pattern from the debug pattern table by its ID.
 * @param pattern_id The ID of the pattern
 * @param bank The bank of the pattern (0 -> 0x0000, 1 -> 0x1000)
 * @return The data of the pattern matching the given ID.
 */
DebugPattern dbg_pattern_get(int pattern_id, int bank);

/**
 * Gets a debug pattern from the debug pattern table by its position.
 * @param x The horizontal position of the pattern
 * @param y The vertical position of the pattern
 * @param bank The bank of the pattern (0 -> 0x0000, 1 -> 0x1000)
 * @return The data of the pattern matching the given positions.
 */
DebugPattern dbg_pattern_get_pos(int x, int y, int bank);

/**
 * Draws a pattern to a buffer. The pattern is determined by its ID.
 * @param pattern_id The ID of the pattern
 * @param bank The bank of the pattern
 * @param buffer The buffer to write the pattern data to
 * @param buffer_width The width of a pixel row in the buffer
 * @param palette The background palette to use
 */
void dbg_pattern_draw(int pattern_id, int bank, pixel *buffer, int buffer_width, int palette);

/**
 * Draws a pattern to a buffer. The pattern is determined by its position.
 * @param x The x position of the pattern in the table
 * @param y The y position of the pattern in the table
 * @param bank The bank of the pattern
 * @param buffer The buffer to write the pattern data to
 * @param buffer_width The width of a pixel row in the buffer
 * @param palette The background palette to use
 */
void dbg_pattern_draw_pos(int x, int y, int bank, pixel *buffer, int buffer_width, int palette);

/**
 * Draws a pattern bank to a buffer. Uses the palette #0.
 * @param bank The bank to draw (0 -> 0x0000, 1 -> 0x1000)
 * @param buffer The buffer to write the patterns data to.
 * @param palette The background palette to use
 */
void dbg_pattern_draw_bank(int bank, pixel *buffer, int palette);

#endif //NES_EMULATOR_DBG_PATTERN_TABLE_H