/* newmenu-log.m,
 */

#include <allegro.h>
#include <stdarg.h>
#include <string.h>
#include "common.h"
#include "newmenu-dirty.h"
#include "newmenu-log.h"
#include "newmenu.h"
#include "seborrhea/seborrhea-font.h"


#define MAX_MESSAGES		16
#define foreach_message(m)	for (m = 0; m < MAX_MESSAGES; m++)


static message_t log_message[MAX_MESSAGES];


static void shift_messages_up(void)
{
    int m;

    if (log_message[0].str) {
	free(log_message[0].str);
	log_message[0].str = NULL;
    }

    for (m = 1; m < MAX_MESSAGES; m++) {
	log_message[m-1].str  = log_message[m].str;
	log_message[m-1].tics = MAX(1*MENU_SECONDS, log_message[m].tics);

	if (not log_message[m].str)
	    return;
    }

    log_message[MAX_MESSAGES-1].str  = NULL;
    log_message[MAX_MESSAGES-1].tics = 0;
}

void append_message(const char *fmt, ...)
{
    int m;
    va_list ap;
    char cat[1024];

    va_start(ap, fmt);
    vsnprintf(cat, sizeof cat, fmt, ap);
    va_end(ap);

    foreach_message (m) {
	if (log_message[m].str)
	    continue;

	log_message[m].str  = strdup(cat);
	log_message[m].tics = 5*MENU_SECONDS;
	return;
    }
}

void update_log(void)
{
    int m;

    foreach_message (m) {
	if (log_message[m].tics > 0)
	    log_message[m].tics--;
    }

    if (log_message[0].tics <= 0)
	shift_messages_up();
}

void draw_log(BITMAP *dest)
{
    static unsigned int previous_width;
    unsigned int w = 0;
    int i, y;
    SebFont *font = [base_sebum getSebumByName:"fonts/elle16"];

    y = 10;

    foreach_message (i) {
	message_t *m = &log_message[i];

	if (!m->str)
	    break;

	w = MAX(w, [font textLength:m->str]);
	[font putString:m->str To:dest X:10 Y:y Colour:0xc0:0x20:0x20];
	y += 16;
    }

    mark_dirty_rectangle(10, 10, MAX(w, previous_width), y+[font textHeight]);

    /* Remember the width of the widest item to clear it properly. */
    previous_width = w;
}
