/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#include <stdio.h>

#include "codetable.h"
#include "hzinput.h"

#define LOOKUP_CHOICE_NUM  	6

#define IME_Status		ime_buffer->return_status
#define Input_Buf		ime_buffer->inputkey_buf
#define Input_Len		ime_buffer->inputkey_len
#define Preedit_Buf		ime_buffer->preedit_buf
#define Preedit_Len		ime_buffer->preedit_len
#define Preedit_CaretPos	ime_buffer->preedit_caretpos
#define Commit_Buf		ime_buffer->commit_buf
#define Commit_Len		ime_buffer->commit_len
#define Status_Buf		ime_buffer->status_buf
#define Status_Len		ime_buffer->status_len
#define Lookup_Buf		ime_buffer->lookup_buf
#define Lookup_Num		ime_buffer->lookup_num
#define Lookup_Pos		ime_buffer->cur_lookup_pos
#define Candidates_Buf		ime_buffer->candidates_buf
#define Additions_Buf		ime_buffer->additions_buf

int Is_UsedCodes_Key(CodeTableStruct *hztbl, int key)
{
	if (index(hztbl->UsedCodes, key))
		return(1);
	else
		return(0);
}

int get_select_num(CodeTableStruct *hztbl, int key)
{
	int ret = -1;
	switch(hztbl->nSelectKeyMode) {
		case NUMBER0_MODE:
			if (key >= '0' && key <= '9')
				ret = (key - '0') % 10;
			break;

		case NUMBER_MODE:
			if (key >= '0' && key <= '9')
				ret = (key - '0' + 9) % 10;
			break;

		case LOWER_MODE:
			if (key >= 'a' && key <= 'a' + 10)
				ret = key - 'a';
			break;

		case UPPER_MODE:
			if (key >= 'A' && key <= 'A' + 10)
				ret = key - 'A';
			break;
	}
	return(ret);
}

int Is_Select_Key(CodeTableStruct *hztbl, int key)
{
	int ret = get_select_num(hztbl, key);
	if (ret == -1)
		return(0);
	else
		return(1);
}

int Is_Commit_Key(CodeTableStruct *hztbl, int key)
{
	if (key == SPACE_KEY || key == RETURN_KEY)
		return(1);
	else
		return(0);
}

int Is_Space_Key(CodeTableStruct *hztbl, int key)
{
	if (key == SPACE_KEY)
		return(1);
	else
		return(0);
}

int Is_BackSpace_Key(CodeTableStruct *hztbl, int key)
{
	int i;
	unsigned char *keylist = hztbl->functionkey[BACKSPACE_KEY_ID].keylist;

	if (key == BACKSPACE_KEY || key == DELETE_KEY)
		return(1);

	if (keylist[0]) {
		for (i=0; i<MAX_FUNCTIONKEY_LEN; i++)
			if (keylist[i] == key)
				return(1);
	}

	return(0);
}

int Is_ClearAll_Key(CodeTableStruct *hztbl, int key)
{
	int i;
	unsigned char *keylist = hztbl->functionkey[CLEARALL_KEY_ID].keylist;

	if (key == ESC_KEY)
		return(1);

	if (keylist[0]) {
		for (i=0; i<MAX_FUNCTIONKEY_LEN; i++)
			if (keylist[i] == key)
				return(1);
	}
	return(0);
}

int Is_NextPage_Key(CodeTableStruct *hztbl, int key)
{
	int i;
	unsigned char *keylist = hztbl->functionkey[PAGEDOWN_KEY_ID].keylist;

	if (key == PAGEDOWN_KEY)
		return(1);

	if (keylist[0]) {
		for (i=0; i<MAX_FUNCTIONKEY_LEN; i++)
			if (keylist[i] == key)
				return(1);
	}
	return(0);
}

int Is_PrevPage_Key(CodeTableStruct *hztbl, int key)
{
	int i;
	unsigned char *keylist = hztbl->functionkey[PAGEUP_KEY_ID].keylist;

	if (key == PAGEUP_KEY)
		return(1);
	
	if (keylist[0]) {
		for (i=0; i<MAX_FUNCTIONKEY_LEN; i++)
			if (keylist[i] == key)
				return(1);
	}
	return(0);
}

int get_lookup_result(CodeTableStruct *hztbl, IMEBufferRec *ime_buffer, 
int nHelpInfoMode, int pos, int max_lookup_num)
{
	int i, lookup_num;

	lookup_num = codetable_search(hztbl, Input_Buf, Candidates_Buf, Additions_Buf, pos, max_lookup_num); 
	if (lookup_num > 0) {
		for (i=0; i<lookup_num; i++) {
/*
			printf("%d: %s %s\n", i, Candidates_Buf[i], Additions_Buf[i]);
*/
			if (nHelpInfoMode)
				sprintf((char *)Lookup_Buf[i], "%s %s", Candidates_Buf[i], Additions_Buf[i]);
			else
				strcpy(Lookup_Buf[i], Candidates_Buf[i]);
		}
	}

	return(lookup_num);

}

int Commit_And_Clean_All_Area(IMEBufferRec *ime_buffer)
{
	Input_Len = 0;
	Preedit_Len = 0;
	Lookup_Num = 0;
	Preedit_CaretPos = 0;
	IME_Status = IME_COMMIT | IME_PREEDIT_AREA | IME_LOOKUP_AREA;
}

int Clean_All_Area(IMEBufferRec *ime_buffer)
{
	Input_Len = 0;
	Preedit_Len = 0;
	Lookup_Num = 0;
	Preedit_CaretPos = 0;
	IME_Status = IME_PREEDIT_AREA | IME_LOOKUP_AREA;
}

int commit_candidate(IMEBufferRec *ime_buffer, int id)
{
	if (id >= Lookup_Num)
		return(-1);

	strcpy((char *)Commit_Buf, (char *)Candidates_Buf[id]);
	Commit_Len = strlen((char *)Commit_Buf);
	Commit_And_Clean_All_Area(ime_buffer);

	return(0);
}

void warning_bell()
{
}

/* return value:  IME_NOT_USED_KEY:  if IME not use this key, return this key to systerm directly */
/*                IME_USED_KEY:      if IME has used this key */
int codetable_filter(CodeTableStruct *hztbl, IMEKey key_event, IMEBufferRec *ime_buffer)
{
    	char    ch;
    	int     i, k, hznum;
	int     key, pos, select_num;

	int 	Max_Lookup_Num = LOOKUP_CHOICE_NUM;
	int 	nKeyByKeyMode = hztbl->nKeyByKeyMode;
	int 	nHelpInfoMode = hztbl->nHelpInfoMode;
	int 	nAutoSelectMode = hztbl->nAutoSelectMode;
	int 	nKeyPromptMode = hztbl->nKeyPromptMode;

	ime_buffer->encode = hztbl->Encode;

	IME_Status = 0;

	key = map_keyevent_to_imekey(hztbl, key_event);
	DEBUG_printf("map_keyevent_to_imekey: return key:0x%x\n", key);

	if (key == IME_NOT_USED_KEY)
		return(IME_NOT_USED_KEY);

	switch(hztbl->nSelectKeyMode) {
		case NUMBER0_MODE:
			ime_buffer->lookup_label_type = NUMERIC0_LABEL;
			break;
		case NUMBER_MODE:
			ime_buffer->lookup_label_type = NUMERIC_LABEL;
			break;
		case LOWER_MODE:
			ime_buffer->lookup_label_type = LOWER_LABEL;
			break;
		case UPPER_MODE:
			ime_buffer->lookup_label_type = UPPER_LABEL;
			break;
		default:
			ime_buffer->lookup_label_type = NUMERIC_LABEL;
	}

    	if(Is_Select_Key(hztbl, key)) {
        	if (Lookup_Num > 0) {
			select_num = get_select_num(hztbl, key);
			if (select_num >= 0 && select_num < Lookup_Num) {
				commit_candidate(ime_buffer, select_num);
			}
			return(IME_USED_KEY);
		}
    	}

    	if((Is_UsedCodes_Key(hztbl, key)) || (Is_Wildchar_Key(hztbl, key))) { 
		/* if inputted keys length has over the limit */
		if (Input_Len >= hztbl->MaxCodes) {
			return(IME_USED_KEY);
		}

        	if (Lookup_Num > 0 && !nKeyByKeyMode) {
			strcpy((char *)Commit_Buf, (char *)Candidates_Buf[0]);
                        Commit_Len = strlen((char *)Commit_Buf);
                        Commit_And_Clean_All_Area(ime_buffer);
        	}

            	Input_Buf[Input_Len] = key;
            	Input_Len ++;
            	Input_Buf[Input_Len] = '\0';
		
		if (nKeyPromptMode) {
			strcpy(Preedit_Buf+Preedit_Len, hztbl->keyprompt[key].prompt);
			Preedit_Len += strlen(hztbl->keyprompt[key].prompt);
            		Preedit_Buf[Preedit_Len] = '\0';
		} else {
			Preedit_Buf[Preedit_Len] = key;
			Preedit_Len += 1;
            		Preedit_Buf[Preedit_Len] = '\0';
		}
		Preedit_CaretPos = Preedit_Len;
		IME_Status |= IME_PREEDIT_AREA;

		Lookup_Num = 0;
		if (nKeyByKeyMode /* || Input_Len == hztbl->MaxCodes */) {
			Lookup_Pos = 0;
		 	Lookup_Num = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, Lookup_Pos, Max_Lookup_Num); 
			/* if Input_Len is MaxCodes, no matter the KeyByKey mode, need do checking */
			if (Input_Len == hztbl->MaxCodes) {
				if (Lookup_Num == 1 && nAutoSelectMode) {
					commit_candidate(ime_buffer, 0);
					return(IME_USED_KEY);
				}
			}
		}
		IME_Status |= IME_LOOKUP_AREA;

		return(IME_USED_KEY);
	}

    	if(Is_ClearAll_Key(hztbl, key)) { 
		/* Esc , clear preedit area, lookup choice area */

		/*  if no inputted key, directly return this key */
		if (Input_Len==0) return(IME_NOT_USED_KEY);

		Clean_All_Area(ime_buffer);

		return (IME_USED_KEY);
    	}

    	if (Is_BackSpace_Key(hztbl, key)) { /* Back Space & Delete */
		/*  if no inputted key, directly return this key */
		if (Input_Len==0) return(IME_NOT_USED_KEY);

        	/* Delete characters in pre-edit region */
            	Input_Len --;
		if (nKeyPromptMode) {
			ch = Input_Buf[Input_Len];
            		Preedit_Len -= strlen(hztbl->keyprompt[ch].prompt);
            		Preedit_Buf[Preedit_Len] = '\0';
		} else {
			Preedit_Len -= 1;
            		Preedit_Buf[Preedit_Len] = '\0';
		}

            	Input_Buf[Input_Len] = '\0';
		Preedit_CaretPos = Preedit_Len;
		IME_Status = IME_PREEDIT_AREA;

		Lookup_Num = 0;
		if ((Input_Len > 0) && nKeyByKeyMode) {
			Lookup_Pos = 0;
		 	Lookup_Num = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, Lookup_Pos, Max_Lookup_Num); 
		}
		IME_Status |= IME_LOOKUP_AREA;

		return(IME_USED_KEY);
    	}

    	if(Is_NextPage_Key(hztbl, key)) {
		/*  if no inputted key, directly return this key */
		if (Input_Len==0) return(IME_NOT_USED_KEY);

		/* if any preedit key and not in Lookup status */
		if (Lookup_Num==0) return(IME_USED_KEY);

		pos = Lookup_Pos + Max_Lookup_Num;
		hznum = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, pos, Max_Lookup_Num); 
		if (hznum > 0) {
			Lookup_Num = hznum;
			Lookup_Pos = pos;
			IME_Status = IME_LOOKUP_AREA;
		} else {
               		warning_bell();
		}

		return(IME_USED_KEY);
    	}

    	if(Is_PrevPage_Key(hztbl, key)) {
		/*  if no inputted key, directly return this key */
		if (Input_Len==0) return(IME_NOT_USED_KEY);

		/* if any preedit key and not in Lookup status */
		if (Lookup_Num==0) return(IME_USED_KEY);

		/* if in beginning pos */
		if (Lookup_Pos<=0) {
               		warning_bell();
			return(IME_USED_KEY);
		}

		pos = Lookup_Pos - Max_Lookup_Num;
		hznum = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, pos, Max_Lookup_Num); 
		if (hznum > 0) {
			Lookup_Num = hznum;
			Lookup_Pos = pos;
			IME_Status = IME_LOOKUP_AREA;
		} else {
               		warning_bell();
		}

		return(IME_USED_KEY);
    	}

    	if(Is_Space_Key(hztbl, key)) {
		/* if no input keys */
		if (Input_Len==0) 
			return(IME_NOT_USED_KEY);

		if (Lookup_Num==0) {
			/* Search from beginning */
			Lookup_Pos = 0;
			Lookup_Num = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, Lookup_Pos, Max_Lookup_Num);
			if (Lookup_Num == 1 && nAutoSelectMode) {
				commit_candidate(ime_buffer, 0);
			} else if (Lookup_Num == 0) {
				warning_bell();
			}
			IME_Status |= IME_LOOKUP_AREA;
			return(IME_USED_KEY);
		}

		/* Space key as scroll key */
		/* if Have several candidates, need search the next page */
		pos = Lookup_Pos + Max_Lookup_Num;
		hznum = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, pos, Max_Lookup_Num); 
		if (hznum == 0) {
			/* if no candidates for the next page */
			if (Lookup_Pos = 0) {
				/* if is the first page, need not do anything */
				return(IME_USED_KEY);
			} else {
				/* if not the first page, need scroll to the first page */
				pos = 0;
				hznum = get_lookup_result(hztbl, ime_buffer, nHelpInfoMode, pos, Max_Lookup_Num); 
			}
		}

		Lookup_Pos = pos;
		Lookup_Num = hznum;
		IME_Status = IME_LOOKUP_AREA;

		return(IME_USED_KEY);
    	}

	/* for unnormal keys */
	if (Lookup_Num > 0) {
		/* need commit the first candidate */
		strcpy((char *)Commit_Buf, (char *)Candidates_Buf[0]);
		Commit_Len = strlen((char *)Commit_Buf);
		Commit_And_Clean_All_Area(ime_buffer);
	}

        return(IME_NOT_USED_KEY);
}
