#include "tele.h"

#define MAX_MENU	15

static Boolean exited;

static int menu_height(menu, n)
DMenu *menu;
int n;
{
	int max;
	char *t;

	max = MAX_MENU;

	if (StatusLine > 24)
		max += StatusLine - 24;

	for (t = menu->prompt; *t; t++)
	{
		if (*t == '\n')
			--max;
	}
	return n > max ? max : n;
}

int dmenuExit(tmp)
dialogMenuItem *tmp;
{
	exited = TRUE;
	return DITEM_LEAVE_MENU;
}

Boolean dmenuOpen(menu, choice, scroll, curr, max, buttons)
DMenu *menu;
int *choice, *scroll, *curr, *max;
Boolean buttons;
{
	int n, rval = 0;
	dialogMenuItem *items;

	items = menu->items;
	if (buttons)
		items += 2;

	for (n = 0; items[n].title; n++);

	while (1)
	{
		char buf[FILENAME_MAX];
		WINDOW *w = savescr();

		use_helpline(menu->helpline);
		use_helpfile(systemHelpFile(menu->helpfile, buf));

		dialog_clear_norefresh();

		if (menu->type & DMENU_NORMAL_TYPE)
			rval = dialog_menu((u_char *)menu->title,
					(u_char *)menu->prompt, -1, -1,
					menu_height(menu, n), -n, items,
					(char *)buttons, choice, scroll);

		else if (menu->type & DMENU_RADIO_TYPE)
			rval = dialog_radiolist((u_char *)menu->title,
					(u_char *)menu->prompt, -1, -1,
					menu_height(menu, n), -n, items,
					(char *)buttons);

		else if (menu->type & DMENU_CHECKLIST_TYPE)
			rval = dialog_checklist((u_char *)menu->title,
					(u_char *)menu->prompt, -1, -1,
					menu_height(menu, n), -n, items,
					(char *)buttons);

		else
			msgFatal("Nieznany typ menu %s -- błąd w programie!\n",
					menu->title);

		if (exited)
		{
			exited = FALSE;
			restorescr(w);
			return TRUE;
		}
		else if (rval)
		{
			restorescr(w);
			return FALSE;
		}
		else if (menu->type & DMENU_SELECTION_RETURNS)
		{
			restorescr(w);
			return TRUE;
		}
	}
}

Boolean dmenuOpenSimple(menu, buttons)
DMenu *menu;
Boolean buttons;
{
	int choice, scroll, curr, max;

	choice = scroll = curr = max = 0;
	return dmenuOpen(menu, &choice, &scroll, &curr, &max, buttons);
}


