#include "log.h"
#include <raylib.h>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void draw_log(Log* log) {
  for(int line_num = 0; line_num < log->line_count; line_num++) {
    DrawText(
	     log->lines[line_num],
	     log->input->position.x,
	     log->input->position.y + ((line_num - log->line_count) * 20),
	     20,
	     RAYWHITE
	     );
  }
}

Log *create_log(void) {
  Log *log = malloc(sizeof(Log));
  log->line_count = 0;
  log->lines = malloc(sizeof(char**));
  return log;
}

#define MAX(a, b) a > b ? a : b
#define MIN(a, b) a < b ? a : b
#define LINE_LENGTH 60

void push_line_to_log(Log* log, char* line) {
  int line_length = MIN(strlen(line), LINE_LENGTH);
  if (line_length == LINE_LENGTH) {
    while (line[line_length] != ' ') line_length--;
  }
  log->lines = realloc(log->lines, (log->line_count + 1) * sizeof(char*));
  log->lines[log->line_count] = malloc(line_length + 1);
  memcpy(log->lines[log->line_count], line, line_length);
  log->lines[log->line_count][line_length] = '\0';
  log->line_count++;

  if (strlen(line) > line_length) {
    push_line_to_log(log, line + line_length + 1);
  }
}

void free_log(Log* log) {
  for(int line_num = 0; line_num < log->line_count; line_num++) {
    free(log->lines[line_num]);
  }
  free(log->lines);
}
