/* ------------------ msgbox.c ------------------ */

#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "dflat.h"

extern DBOX MsgBox;

int MessageBoxProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case CREATE_WINDOW:
			GetClass(wnd) = MESSAGEBOX;
			ClearAttribute(wnd, CONTROLBOX);
			break;
		default:
			break;
	}
	return BaseWndProc(MESSAGEBOX, wnd, msg, p1, p2);
}

int YesNoBoxProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case CREATE_WINDOW:
			GetClass(wnd) = MESSAGEBOX;
			ClearAttribute(wnd, CONTROLBOX);
			break;
		case KEYBOARD:	{
			int c = tolower((int)p1);
			if (c == 'y')
				SendMessage(wnd, COMMAND, ID_OK, 0);
			else if (c == 'n')
				SendMessage(wnd, COMMAND, ID_CANCEL, 0);
			break;
		}
		default:
			break;
	}
	return BaseWndProc(MESSAGEBOX, wnd, msg, p1, p2);
}

int ErrorBoxProc(WINDOW wnd, MESSAGE msg, PARAM p1, PARAM p2)
{
	switch (msg)	{
		case CREATE_WINDOW:
			GetClass(wnd) = ERRORBOX;
			ClearAttribute(wnd, MOVEABLE | CONTROLBOX);
			break;
		default:
			break;
	}
	return BaseWndProc(ERRORBOX, wnd, msg, p1, p2);
}

static int GenericMessage(char *ttl, char *msg, int buttonct,
	int (*wndproc)(struct window *, enum messages, PARAM, PARAM),
	char *b1, char *b2)
{
	int rtn;
	MsgBox.dwnd.title = ttl;
	MsgBox.ctl[0].dwnd.h = MsgHeight(msg);
	MsgBox.ctl[0].dwnd.w = max(MsgWidth(msg),
			buttonct*8 + buttonct + 2);
	MsgBox.dwnd.h = MsgBox.ctl[0].dwnd.h+6;
	MsgBox.dwnd.w = MsgBox.ctl[0].dwnd.w+4;
	if (buttonct == 1)
		MsgBox.ctl[1].dwnd.x = (MsgBox.dwnd.w - 10) / 2;
	else	{
		MsgBox.ctl[1].dwnd.x = (MsgBox.dwnd.w - 18) / 2;
		MsgBox.ctl[2].dwnd.x = MsgBox.ctl[1].dwnd.x + 9;
		MsgBox.ctl[2].class = BUTTON;
	}
	MsgBox.ctl[1].dwnd.y = MsgBox.dwnd.h - 4;
	MsgBox.ctl[2].dwnd.y = MsgBox.dwnd.h - 4;
	MsgBox.ctl[0].itext = msg;
	MsgBox.ctl[1].itext = b1;
	MsgBox.ctl[2].itext = b2;
	rtn = DialogBox(NULLWND, &MsgBox, wndproc);
	MsgBox.ctl[2].class = 0;
	return rtn;
}

int TestErrorMessage(char *msg)
{
	return GenericMessage("Error", msg, 2, ErrorBoxProc, Ok, Cancel);
}

void ErrorMessage(char *msg)
{
	GenericMessage("Error", msg, 1, ErrorBoxProc, Ok, NULL);
}

void MessageBox(char *ttl, char *msg)
{
	GenericMessage(ttl, msg, 1, MessageBoxProc, Ok, NULL);
}

int YesNoBox(char *msg)
{
	return GenericMessage(NULL, msg, 2, YesNoBoxProc, Yes, No);
}
