//
// Created by bruno on 5.2.2025.
// Modified to use dynamic limits.
//
#ifndef RISCB_TEXTEDITOR_H
#define RISCB_TEXTEDITOR_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <SDL2/SDL_rect.h>
#include <SDL2/SDL_surface.h>
#include <SDL2/SDL_render.h>
#include "font.h"
#include "../cpu/core.h"

typedef struct {
    char *text;   // Dynamically allocated string for this line
    int active;   // Flag to check if the line is in use
} Line;

typedef struct {
    Line *lines;            // Dynamic array of lines
    int line_count;         // Number of active lines
    int maxLines;      // Maximum number of lines (e.g. assembly lines)
    int max_line_width;     // Maximum characters per line (excluding '\0')
    int displayLineCount;  // Maximum number of lines for display

    int cursor_line;        // Current cursor line
    int cursor_line_offset; // Display offset (first line in the display)
    int cursor_pos;         // Current cursor position in line

    char *outputString;     // Dynamically allocated output string (size: max_line_width * maxLines + 1)
    char *displayString;    // Dynamically allocated display string (size: max_line_width * displayLineCount + 1)
    SDL_Rect *rect;
    SDL_Rect *outRect;
    SDL_Texture *texture;
    bool readOnly;
    BitmapFont *font;
    SDL_Rect *cursorRect;
    SDL_Rect *highlightedLineRect;
} TextEditor;

// Initialize the text editor. The parameters max_line_width, maxLines, and displayLineCount
// determine the dynamic sizes for the text editor.
void init_editor(TextEditor *editor, BitmapFont *font, int x, int y, SDL_Renderer *renderer,
                 int max_line_width, int max_lines_asm, int max_lines_display, bool readOnly);

// Other function prototypes remain mostly unchanged but will use the dynamic limits:
void insert_line(TextEditor *editor, int position, const char *text, SDL_Renderer *renderer);

void insert_line_rel(TextEditor *editor, SDL_Renderer *renderer);

void editor_render(TextEditor *editor, SDL_Renderer *renderer, CPU *cpu, uint8_t editorIndex, bool isActive, bool cursorBlink);

void remove_character(TextEditor *editor, bool isDelete, SDL_Renderer *renderer);

void insert_character(TextEditor *editor, char ch, SDL_Renderer *renderer);

void move_cursor(TextEditor *editor, int new_line, int new_pos, bool keepPos, SDL_Renderer *renderer);

void move_cursor_relative(TextEditor *editor, int line_offset, int pos_offset, bool keepPos, SDL_Renderer *renderer);

void generate_string_display(TextEditor *editor, SDL_Renderer *renderer);

void generate_string(TextEditor *editor);

void fill_editor_from_string(TextEditor *editor, const char *content, int lineStart, bool isComplete,
                             SDL_Renderer *renderer);

// A cleanup function to free dynamically allocated memory.
void destroy_editor(TextEditor *editor);

#endif // RISCB_TEXTEDITOR_H
