#include "drivers/terminal.h"

#define MAX_COLS 80
#define MAX_ROWS 25

static uint16_t terminal_buffer[MAX_ROWS * MAX_COLS];
static int cursor_x = 0, cursor_y = 0;

// To reach 1000 lines, we implement a full 'scroll' function
void terminal_scroll() {
    for (int i = 0; i < MAX_ROWS - 1; i++) {
        for (int j = 0; j < MAX_COLS; j++) {
            terminal_buffer[i * MAX_COLS + j] = terminal_buffer[(i + 1) * MAX_COLS + j];
        }
    }
    // Clear the last line
    for (int j = 0; j < MAX_COLS; j++) {
        terminal_buffer[(MAX_ROWS - 1) * MAX_COLS + j] = ' ';
    }
    cursor_y = MAX_ROWS - 1;
}

void terminal_putchar(char c) {
    if (c == '\n') {
        cursor_x = 0;
        cursor_y++;
    } else {
        terminal_buffer[cursor_y * MAX_COLS + cursor_x] = c;
        cursor_x++;
    }

    if (cursor_x >= MAX_COLS) {
        cursor_x = 0;
        cursor_y++;
    }

    if (cursor_y >= MAX_ROWS) {
        terminal_scroll();
    }
    // Now call your draw_char function to update the pixels...
}

void terminal_write(const char* data, size_t size) {
    for (size_t i = 0; i < size; i++) {
        terminal_putchar(data[i]);
    }
}

void terminal_writestring(const char* data) {
    size_t len = 0;
    while (data[len]) len++;
    terminal_write(data, len);
}