#include <stddef.h>
#include <stdint.h>

#include <lib/stream.h>

#include <drivers/vga/vga.h>

#include <common.h>
#include <memory/mm.h>

static uint32_t framebuffer_address;
static uint32_t framebuffer_width;
static uint32_t framebuffer_height;
static uint32_t framebuffer_total_pixels;
static uint32_t framebuffer_pitch;
static uint32_t framebuffer_bpp;

void vga_init(
	uint32_t fb_paddr,
	uint32_t fb_width,
	uint32_t fb_height,
	uint32_t fb_pitch,
	uint8_t fb_bpp
) {
	uint32_t fb_size_bytes = fb_height * fb_pitch;
	uint32_t num_pages = (fb_size_bytes + 4095) / 4096; 
	for (uint32_t i = 0; i < num_pages; i++) {
		uint32_t phys_addr = fb_paddr + (i * 4096);
		uint32_t virt_addr = VGA_FRAMEBUFFER + (i * 4096);
		map_page(virt_addr, phys_addr, PAGE_PRESENT | PAGE_WRITABLE);
	}

	framebuffer_address = VGA_FRAMEBUFFER;
	framebuffer_width = fb_width;
	framebuffer_height = fb_height;
	framebuffer_pitch = fb_pitch;
	framebuffer_bpp = fb_bpp;
	framebuffer_total_pixels = framebuffer_width * framebuffer_height;

	vga_clear_scrn(0x000000FF);
}

uint32_t vga_get_pitch() {
	return framebuffer_pitch;
}

void vga_clear_scrn(uint32_t color) {
	if (framebuffer_address == 0) return;

	for (uint32_t y = 0; y < framebuffer_height; y++) {
        uint32_t* row = (uint32_t*)((uintptr_t)framebuffer_address + (y * framebuffer_pitch));
        for (uint32_t x = 0; x < framebuffer_width; x++) {
            row[x] = color;
        }
    }
}

void vga_drawchar(char c, int x, int y, psf_font_t* font) {

}

uint32_t vga_write(vfs_node_t* node, uint32_t offset, uint32_t size, uint8_t* buf) {
	// probably just memcpy here
	return size;
}