/* Original Code by Dan */
/* Revised by Stephen B. For MAMED */
#include "launcher.h"

static int count, total;
static int state;

enum states { 
	STATE_WAITING,
	STATE_FADING,
	STATE_WRITING,
	STATE_CLEARING,
	STATE_CURSOR_RET };

static const char * text = NULL;
static const char * text_next = NULL;
static int text_ptr;

int popup_init() { return 0; }

int popup_reload() {
	count = 120;
	text_ptr = 0;
	state = STATE_WAITING;

	return 0;
}

void popup_shutdown() { }

void popup_set_text(const char *txt) {
	text_next = txt;
	if (text == NULL)
		text = text_next;
}

void popup_set_text_now(const char *txt) {
	text = txt;
	text_next = NULL;
}

void popup_clear() {
	if (state != STATE_CLEARING) {
		state = STATE_CLEARING;
		count = -65536;
	}
}

void popup_frame() {
	int i;
	float alpha, x1, y1;

	alpha = 1.0f;
	x1 = 320.0f - 256.0f; y1 = 480.0f - 64.0f;

	if (state == STATE_WAITING) {
		if (count > 0) {
			count--;
		} else {
			state = STATE_FADING;
			count = 0;
		}
		return;
	}

	if (state == STATE_FADING) {
		draw_box(x1, y1, 1024.0f, 512.0f, FONT_HEIGHT*3.0f/2.0f,
			(count / 100.0f), 0.0f, 0.0f, 0.0f);

		count++;
		if (count >= 60) {
			state = STATE_WRITING;
			count = 15;
		}
		return;
	}

	if (state == STATE_CLEARING) {
		if (count == -65536) {
			total = count = FONT_WIDTH * (text_ptr+1);
		}

		alpha = (float)count / (float)total;
		count-=4;
		
		if (count <= 0) {
			text = text_next;
			text_ptr = 0;
			state = STATE_WRITING;
			count = 3;
		}
		draw_box(x1, y1, 1024.0f, 512.0f, FONT_HEIGHT*3.0f/2.0f, 0.6f, 0.0f, 0.0f, 0.0f);
		x1 += 2.0f; y1 += (FONT_HEIGHT/2)*2.0f/3.0f;
		draw_string(x1, y1, 1025.0f,
			alpha, 1.0f, 1.0f, 1.0f, text, text_ptr+1);
		draw_cursor(x1 + count, y1, 1026.0f, 1.0f, 1.0f, 1.0f);
		return;
	}

	/* implicit: STATE_DRAWING */
	draw_box(x1, y1, 1024.0f, 512.0f, FONT_HEIGHT*3.0f/2.0f, 0.6f, 0.0f, 0.0f, 0.0f);
	x1 += 2.0f; y1 += (FONT_HEIGHT/2)*2.0f/3.0f;
	if (text[text_ptr+1])
		draw_cursor(x1 + FONT_WIDTH*(text_ptr+1) + FONT_WIDTH - count*FONT_WIDTH/3.0f,
			y1, 1026.0f, 1.0f, 1.0f, 1.0f);
	else
		draw_cursor(x1 + FONT_WIDTH*(text_ptr+1),
			y1, 1026.0f, 1.0f, 1.0f, 1.0f);


	draw_text_header();
	for (i=0; i<=text_ptr; i++) {
		if (i == text_ptr && text[text_ptr+1]) {
			draw_char(x1 + i*FONT_WIDTH, y1, 1025.0f,
				alpha * (1.0f - (count / 3.0f)), 1.0f, 1.0f, 1.0f, text[i]);
		} else
			draw_char(x1 + i*FONT_WIDTH, y1, 1025.0f,
				alpha, 1.0f, 1.0f, 1.0f, text[i]);
	}
	
	if (count > 0) {
		count--;
		return;
	}
	count = 3;

	/* Timed out, draw a new char */
	if (text[text_ptr+1]) {
		text_ptr++;
	}
}


