/*----------------------------------------------------------------------------
 LIME - The definitive LInux MEnuing system
 (C)opyright 1994-1995, Scott Burkett, All Rights Reserved
 ----------------------------------------------------------------------------- 
 $Header$
 ----------------------------------------------------------------------------- 
 $Log$
 ----------------------------------------------------------------------------*/

#include <stdio.h>
#include <ctype.h>
#include <ncurses.h>

#include "lime.h"

/*    type:  0 = alpha   1 = numeric  2 = ALPHACAPS
      mode:  0 = echo    1 = password
   _forced:  0 = No      1 = Yes
*/

char keybuf[100];

char *GetString(int type, int mode, int _forced, int maxlen)
{
	int x, cntr=0;
	char mask[100];
	unsigned char key;

	/* Display field mask */
	 
	SetColor(ANSI_NORMAL, ANSI_FCYAN, ANSI_BBLACK);
	mask[0]='[';
	for(x=1; x<=maxlen;x++)
		mask[x]='.';

	mask[x]=']';
	mask[x+1]='\0';
	printf(mask);
	
	for(x=1; x<maxlen+2;x++)
		printf("\b");

	fflush(stdout);

	SetColor(ANSI_BRIGHT, ANSI_FWHITE, ANSI_BBLACK);
	keybuf[0] = '\0';

	/* Get input */
	while ( TRUE )
	{
		key = getch();

		SetAlarm();

		if ( key == '\b' || key == 127 )	
		{
			cntr--;
			if( cntr < 0) {
				cntr = 0;
			} else {
				keybuf[cntr] = '\0';
				printf("\b.\b");
				fflush(stdout);
			}
			continue;
		}

		if ( key == '\r' || key == '\n' )
		{
			if(_forced && ( strlen(keybuf) < 1 ))
				continue;
			else
				break;
		}
		
		if( type == NUMERIC && (key < '0' || key > '9'))
			continue;
	
		/* Cheap noise and control character filter */	
		if(key < 32 || key > 127)
			continue;

		keybuf[cntr] = key;
		keybuf[cntr+1] = '\0';
		cntr++;

		if ( cntr > maxlen )
		{
			keybuf[cntr] = '\0';
			cntr--;
			continue;
		}
		
		if ( mode )
			printf("*");
		else
			if(type == ALPHA)
				printf("%c", key);
			else
				printf("%c", toupper(key));

		fflush(stdout);
	}	

	return((char *) &keybuf);
}

void PressEnter(void)
{
	if(!stdscr)
		return;

	SetColor(ANSI_NORMAL, ANSI_FCYAN, ANSI_BBLACK);
	printf("[");
	SetColor(ANSI_BRIGHT, ANSI_FCYAN, ANSI_BBLACK);
	printf("-> Any Key! <-");
	SetColor(ANSI_NORMAL, ANSI_FCYAN, ANSI_BBLACK);
	printf("]");

	kernel();

	flushinp();
	fflush(stdout);
	getch();
	SetAlarm();
	ColorStr("white on black");
}

char PagePrompt(char *keylist, char *keydisp)
{
	char key, *ptr;

	SetColor(ANSI_NORMAL, ANSI_FCYAN, ANSI_BBLACK);
	printf("[");
	SetColor(ANSI_BRIGHT, ANSI_FCYAN, ANSI_BBLACK);
	printf(keydisp);
	SetColor(ANSI_NORMAL, ANSI_FCYAN, ANSI_BBLACK);
	printf("]: ");

	fflush(stdin);
	fflush(stdout);

	do 
	{
		kernel();
		key = getch();
		key = toupper(key);

		SetAlarm();
	
		ptr = keylist;
		while(*ptr != '\0') 
		{
			if(*ptr == key || key == '\r' || key == '\n')
				return(key);
			ptr++;
		}

	} while(key);

	return('\0');

}
