#include "window.h"
#include "print.h"

// Define the screen dimensions
#define SCREEN_WIDTH 80
#define SCREEN_HEIGHT 25

// Function to draw the border of the window
static void draw_border(const Window* win) {
    // Set the color for the border
    print_set_color(win->border_color, win->border_color);

    // Draw top border
    for (int i = 0; i < win->size_x; ++i) {
        move_print_cursor(win->x + i, win->y);
        print_char('#');
    }

    // Draw bottom border
    for (int i = 0; i < win->size_x; ++i) {
        move_print_cursor(win->x + i, win->y + win->size_y - 1);
        print_char('#');
    }

    // Draw left and right borders
    for (int i = 1; i < win->size_y - 1; ++i) {
        move_print_cursor(win->x, win->y + i);
        print_char('#');
        move_print_cursor(win->x + win->size_x - 1, win->y + i);
        print_char('#');
    }

    // Draw title
    if (win->title[0] != '\0') {
        print_set_color(win->border_color, win->background_color);
        move_print_cursor(win->x + 1, win->y);
        print_str(win->title);
    }
}

// Function to draw the background of the window
static void draw_background(const Window* win) {
    // Set the color for the background
    print_set_color(win->background_color, win->background_color);

    for (int i = 1; i < win->size_y - 1; ++i) {
        for (int j = 1; j < win->size_x - 1; ++j) {
            move_print_cursor(win->x + j, win->y + i);
            print_char(' '); // Background character
        }
    }
}

// Function to create a simple window with border, background, and title
void create_window(Window* win, int x, int y, int size_x, int size_y, uint8_t border_color, uint8_t background_color, const char* title) {
    win->x = x;
    win->y = y;
    win->size_x = size_x;
    win->size_y = size_y;
    win->border_color = border_color;
    win->background_color = background_color;

    // Copy title to window struct
    for (int i = 0; i < WINDOW_TITLE_MAX_LENGTH - 1 && title[i] != '\0'; ++i) {
        win->title[i] = title[i];
    }
    win->title[WINDOW_TITLE_MAX_LENGTH - 1] = '\0'; // Ensure null-termination

    // Draw the window
    draw_background(win);
    draw_border(win);
}

// Function to print text inside the window
void print_text_in_window(const Window* win, int x, int y, const char* text) {
    // Set the color for the text
    print_set_color(PRINT_COLOR_WHITE, win->background_color);

    for (int i = 0; text[i] != '\0'; ++i) {
        if (x + i < win->size_x - 1 && y < win->size_y - 1) {
            move_print_cursor(win->x + x + i, win->y + y);
            print_char(text[i]);
        }
    }
}
