/*

8086|Printman/POSTCARD Version 1.00a
選択肢入力処理ルーチン

Copyright (c) 1993 Delmonta
*/

#include<string.h>
#include<ctype.h>
#include"dprint.h"

static	struct MENUDAT	*Menu;
static	int		Selectpos;

/*---------------------------------------------------------------------------*/

static	void	putchoices(int pos)
{
	if	(pos == Selectpos)
		printf("\033[" VAL2STR(ERRMES_LINE-1) ";1f\033[2K%s\033[7m",
							Menu[pos].explain);

	printf("\033[%d;5f%c･%s\033[0m",pos+SYSLINE_START+2,
				Menu[pos].headchar,Menu[pos].tbl);
}

/*---------------------------------------------------------------------------*/

static	void	dpsel_end(void)
{
	unsigned	i;

	printf("\033[" VAL2STR(SYSLINE_START) ";1f");

	for	(i=SYSLINE_START ; i<ERRMES_LINE ; i++)
		printf("\033[2K\n");
}

/*---------------------------------------------------------------------------*/

int	dp_menuselect(char *mes,unsigned num,struct MENUDAT menu[])
{
	int		i;
	char		c;

	Menu      = menu;	/* 値を下請けの関数と共有するための配慮 */

	Selectpos = 0; 

	printf("\033[" VAL2STR(SYSLINE_START) ";1f%s",mes);


			/* コンソール本来のカーソルが画面上に残るため	*/
			/* いちばん上の行を最後に表示したい		*/
	for	(i=num-1 ; i>=0 ; i--)
		putchoices(i);

dpsel_rep:
	c = dp_getch();

	if	(c==EXTKEY_H)
	{
		dp_getch();
		goto dpsel_rep;
	}

	if	(c==UPKEY && Selectpos>0)	/* 上カーソルキー */
	{
		putchoices(Selectpos--);
		putchoices(Selectpos  );
	}
	else if	(c==DOWNKEY && Selectpos<num-1)	/* 下カーソルキー */
	{
		putchoices(Selectpos++);
		putchoices(Selectpos  );
	}
	else if	(c=='\033')
	{
		dpsel_end();
		return -1;
	}
	else if	(c=='\r')
	{
		dpsel_end();
		return Selectpos;
	}
	else
	{
		c = toupper(c);

		for	(i=0 ; i<num ; i++)
		{
			if	(c==Menu[i].headchar)
			{
				dpsel_end();
				return i;
			}
		}

		putchar('\7');
	}

	goto dpsel_rep;
}
