#include <atari.h>
#include <stdio.h>
#include "irc.h"
#include <conio.h>
#include "conio.h"

#define MAX_INPUT_LEN 119

static char input_buffer[MAX_INPUT_LEN + 1];
static short inbuf_len = 0;

void ui_init(void) {
	OS.escflg = 0;
	inbuf_len = input_buffer[0] = 0;
}

void ui_start_msg() {
	/* TODO: use msg_src and msg_dest to decide which window to
	   print to (when we have multi-window support) */
	OS.crsinh = 1;
	putchar(CH_DELLINE);
}

void ui_end_msg(void) {
	OS.crsinh = 0;
	// putchar(CH_EOL); // NO!
	if(inbuf_len) print(input_buffer);
}

void ui_print(const char *str) {
	OS.escflg = 0x80;
	print(str);
	OS.escflg = 0;
}

void ui_putchar(char c) {
	putchar(c);
}

void ui_keystroke(void) {
	char c;

	OS.escflg = 0x80;

	/* pressing ctrl-3 (aka EOF) crashes cc65-compiled binaries *hard*,
	   so don't allow it. */
	if(OS.ch == (KEY_3 | KEY_CTRL)) {
		OS.ch = KEY_NONE;
		return;
	}

	c = cgetc();

	if(c == CH_EOL && !inbuf_len)
		return; /* ignore empty message */

	if(c == CH_DEL && inbuf_len) {
		OS.escflg = 0;
		putchar(c);
		OS.escflg = 0x80;
		input_buffer[inbuf_len--] = 0;
	} else if(inbuf_len == MAX_INPUT_LEN) {
		return; /* ignore */
	} else {
		putchar(c);
		input_buffer[inbuf_len++] = c;
		input_buffer[inbuf_len] = 0;
		if(c == CH_EOL) {
			cmd_command(input_buffer);
			ui_init();
		}
	}
}
