#include "tele.h"

WINDOW *savescr(void)
{
	WINDOW *w;

	w = dupwin(newscr);
	return w;
}

void restorescr(w)
WINDOW *w;
{
	touchwin(w);
	wrefresh(w);
	delwin(w);
}

Boolean file_readable(fname)
char *fname;
{
	if (!access(fname, F_OK))
		return TRUE;
	return FALSE;
}

WINDOW *openLayoutDialog(helpfile, title, x, y, width, height)
char *helpfile, *title;
int x, y, width, height;
{
	WINDOW *win;
	static char help[PATHMAX];

	win = newwin(LINES, COLS, 0, 0);

	if (win)
	{
		if (helpfile)
		{
			use_helpline("Naci¶nij F1 aby uzyskać pomoc.");
			use_helpfile(systemHelpFile(helpfile, help));
		}

		draw_box(win, y, x, height, width, dialog_attr, border_attr);
		wattrset(win, dialog_attr);
		mvwaddstr(win, y, x + (COLS - strlen(title)) / 2, title);
	}
	return win;
}

ComposeObj *initLayoutDialog(win, layout, x, y, max)
WINDOW *win;
Layout *layout;
int x, y, *max;
{
	ComposeObj *obj = NULL, *first;
	int n;

	n = 0;
	while (layout[n].help != NULL)
	{
		int t = TYPE_OF_OBJ(layout[n].type);

		switch (t)
		{
			case STRINGOBJ:
				layout[n].obj = NewStringObj(win,
						layout[n].prompt,
						layout[n].var,
						layout[n].y + y,
						layout[n].x + x,
						layout[n].len,
						layout[n].maxlen);

				((StringObj *)layout[n].obj)->attr_mask =
					ATTR_OF_OBJ(layout[n].type);

				break;

			case BUTTONOBJ:
				layout[n].obj = NewButtonObj(win,
						layout[n].prompt,
						layout[n].var,
						layout[n].y + y,
						layout[n].x + x);

				break;

			default:
				msgFatal("Obiekt nie obsługiwany");
		}

		AddObj(&obj, t, (void *) layout[n].obj);
		n++;
	}

	*max = n - 1;
	for (first = obj; first->prev; first = first->prev);
	return first;
}

int layoutDialogLoop(win, layout, obj, n, max, cbutton, cancel)
WINDOW *win;
Layout *layout;
ComposeObj **obj;
int *n, max, *cbutton, *cancel;
{
	char help_line[80];
	int ret, i, len = strlen(layout[*n].help);

	for (i = 0; i < 79; i++)
		help_line[i] = (i < len) ? layout[*n].help[i] : ' ';

	help_line[i] = '\0';
	use_helpline(help_line);
	display_helpline(win, LINES - 1, COLS - 1);
	wrefresh(win);

	ret = PollObj(obj);
	switch (ret)
	{
		case SEL_ESC:
			*cancel = TRUE;
			return FALSE;

		case KEY_DOWN:
		case SEL_CR:
		case SEL_TAB:
			if (*n < max)
				++*n;
			else
				*n = 0;
			break;

		case SEL_BUTTON:
			if (cbutton && *cbutton)
				*cancel = TRUE;
			else
				*cancel = FALSE;
			return FALSE;

		case KEY_UP:
		case SEL_BACKTAB:
			if (*n)
				--*n;
			else
				*n = max;
			break;

		case KEY_F(1):
			display_helpfile();

		default:
			beep();

	}
	return TRUE;
}

