/* newmenu-hiscore.m,
 */

#include <allegro.h>
#include <math.h>
#ifndef NO_FBLEND
# include "fblend/include/fblend.h"
#endif
#include "common.h"
#include "hiscore.h"
#include "input.h"
#include "newmenu-dirty.h"
#include "newmenu-hiscore.h"
#include "newmenu.h"
#include "seborrhea/seborrhea-font.h"
#include "seborrhea/seborrhea.h"


void roll_high_scores(BITMAP *dbuf)
{
    BOOL exit = NO, redraw = YES;
    SebFont *name_font, *score_font;
    Sebum<SebImage> *bg;
    int c, i, t = 0, y, timeout;

    bg = [menu_sebum getSebumByName:"hiscore"];
    name_font  = (SebFont *)[base_sebum getSebumByName:MENU_FONT_NAME];
    score_font = (SebFont *)[base_sebum getSebumByName:"fonts/digital2"];
    [name_font  setFontSize:24];
    [score_font setFontSize:24];

    [bg drawTo:dbuf X:0 Y:0 W:dbuf->w H:dbuf->h];
    mark_entire_screen_dirty();

    timeout = 8*MENU_SECONDS;

    while (not (exit || emergency_exit)) {
	while (counter) {
	    counter--;
	    redraw = YES;

	    if (t < 20*NUM_HIGH_SCORE_ITEMS)
		t++;
	    else
		timeout--;

	    menu_common_update();

	    if (okay_released() || menu_released() || timeout <= 0)
		exit = YES;

	    rest(0);
	}

	if (redraw && not exit) {
	    redraw = NO;
	    /* blit(bg, dbuf, 0, 0, 0, 0, bg->w, bg->h); */

	    for (i = 0, y = 140; i < NUM_HIGH_SCORE_ITEMS; i++, y += 30) {
		BOOL mark_dirty = YES;
		int r = MAX(0xc0 - i*0x05, 0);
		int g = MAX(0x40 - i*0x02, 0);
		int b = MAX(0x40 - i*0x02, 0);

		/* We have not yet appeared on the screen. */
		if (t - i*20 < 0)
		    break;

		[bg drawFromX:0 Y:y To:dbuf X:0 Y:y W:dbuf->w H:30];

		if (t - i*20 < 20) {
		    /* We recently appeared onto the screen. */
		    r = MIN(0xff, r*(50-(t-i*20))/30);
		    g = MIN(0xff, g*(50-(t-i*20))/30);
		    b = MIN(0xff, b*(50-(t-i*20))/30);

#ifndef NO_FBLEND
		    /* Red underline. */
		    fblend_rect_trans(dbuf, 125, y+20, SCREEN_W-250, 4,
				      makecol(0xff, 0x00, 0x00), 10*(20-(t-i*20)));
#endif
		}
		elif (t - i*20 < 25) {
		    /* We recently finished glowing on the screen.
		       Make sure our picture is correct.  */
		}
		else {
		    /* We have been shown. */
		    mark_dirty = NO;
		}

		c = makecol(r,g,b);

		[score_font putStringTo:dbuf X:240 Y:y Colour:r:g:b Alignment:ALIGN_RIGHT Decoration:DECORATION_OUTLINE :"%d", high_score_item[i].score];
		[name_font putString:high_score_item[i].name To:dbuf X:260 Y:y Colour:r:g:b Decoration:DECORATION_OUTLINE];

		if (mark_dirty)
		    mark_dirty_rectangle(0, y, dbuf->w, 30);
	    }

	    blit_dirty_rectangles(dbuf, screen);
	}
    }

    [name_font setFontSize:MENU_FONT_SIZE];
}
