/*
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 <sys/stat.h>
#include <dlfcn.h>

#include "hzinput.h"
#include "xaux_locale.h"
#include "encode.h"

#define MAX_LINE_LEN	256

int       	gEngine_Num;
IMEEngineRec 	*gEngine_Info[MAX_ENGINE_NUM];

/* 
read profile from file "sysime.cfg" to memory buffer   
the struct of sysime.cfg is as follow:

# comments
# locale_name can be "common", means the engine in common section 
# can be used for all the locales that the language engine support. 
# engine_options can be the path of the dictionary or options that
# the engine can recognize.
[ locale_name ]
	engine_name		engine_path	engine_options

for example:
[ zh_CN.EUC ]  
	NewPY_gb	common/NewPY.so		GB2312|PinYinMode
	NewSP_gb	common/NewPY.so		GB2312|ShuangPinMode
	NeiMa_gb2312	common/NeiMa.so		GB2312

[ zh_CN.GBK ]  
	NewPY_gbk	common/NewPY.so		GBK|PinYinMode
	NewSP_gbk	common/NewPY.so		GBK|ShuangPinMode
	NeiMa_gbk	common/NeiMa.so		GBK

[ common ]
	WuBi		common/ctim.so		common/data/wubi.data 	7

*/ 

void get_ime_line(FILE *fd, char *line);

void  print_core()
{
     	int i;

     	DEBUG_printf("gEngine_Num:%d\n", gEngine_Num);
     	for (i=0; i<gEngine_Num; i++) {
          	DEBUG_printf("localeid:%d, imid:%d, ename:%s, cname:%s, status:%d\n", 
 			gEngine_Info[i]->core.baseinfo.locale_id,
			gEngine_Info[i]->core.baseinfo.engine_id,
 			gEngine_Info[i]->core.baseinfo.ename,
			gEngine_Info[i]->core.baseinfo.cname,
			gEngine_Info[i]->core.baseinfo.status);
	}
}

int  hzinput_init()
{
    	char            file_name[256], line[MAX_LINE_LEN]; 
	char		*engine_name, *engine_path, *engine_options;
	char		locale_name[128], *kptr, *ptr;
    
	int  		len, i;
	int		locale_flag = ENCODE_ERROR;
	FILE 		*fd;

    	gEngine_Num = 0;
	for (i=0; i<MAX_ENGINE_NUM; i++)
		gEngine_Info[i] = NULL;

    	sprintf(file_name, "%s/%s/%s",  DEFAULT_ENGINE_PATH, 
					XAUX_LOCALE_NAME, 
					SYSTEM_PROFILE_NAME);

    	DEBUG_printf("file name :%s\n",file_name);
	fd = fopen(file_name, "r");
	if (! fd)
		return (-1);

	do {
		get_ime_line(fd, line);

		if (line[0] == '\0') break;
		if (line[0] == '#') continue;

		len = strlen(line);
		if (line[0] == '[' && line[len-1] == ']') {
			/* compute locale_flag */
			ptr = line + 1;
			while(isspace(*ptr)) ptr++;

			/* get locale section name */
			kptr = locale_name;
			while (*ptr && !isspace(*ptr) && *ptr!=']') 
				*(kptr++) = *(ptr++);
			*kptr = '\0';

			/* get locale section name */
			if (!strncasecmp(locale_name, COMMON_ENGINE_PATH, strlen(COMMON_ENGINE_PATH)))
				locale_flag = ENCODES_NUM;
			else
				locale_flag = get_encodeid_from_locale(locale_name);

			DEBUG_printf("locale_name:%s, locale_id:%d\n", locale_name, locale_flag);
			continue;

		}

		if (locale_flag == ENCODE_ERROR) continue;

		/* get IME language engine name */
		ptr = line;
		engine_name = line;
		while (*ptr && !isspace(*ptr)) ptr++;
		if (*ptr) {
			*ptr = '\0';
			ptr++;
		}
		
		while (*ptr && isspace(*ptr)) ptr++;
		engine_path = ptr;

		while (*ptr && !isspace(*ptr)) ptr++;
		if (*ptr) {
			*ptr = '\0';
			ptr++;
		}
		
		while (*ptr && isspace(*ptr)) ptr++;
		engine_options = ptr;

		DEBUG_printf("locale_id:%d, locale:%s, Engine Name:%s\n", 
			locale_flag, locale_name, engine_name, 
			engine_path, engine_options);

		open_engine(locale_flag, locale_name, 
			    engine_name, engine_path, engine_options);

	} while (1);

	fclose(fd);

    	print_core();

    	return 0;
}

void get_ime_line(FILE *fd, char *line)
{
	int line_ptr;
	char line_buf[256], *ptr;

	line_ptr = 0;
	line[0] = '\0';

	/* get line with no space */
 	while(fgets(line_buf, 255, fd) != NULL) {
		ptr = line_buf;

		/* skip space keys */
		while(*ptr && isspace(*ptr)) ptr++;

		/* if is space line, get new line */
		if (*ptr == '\n' || *ptr == '\0')
			continue;

		while(*ptr != '\n' && *ptr != '\0' && line_ptr < MAX_LINE_LEN) 
			line[line_ptr++] = *ptr++;

		/* trim right space */
		while (isspace(line[line_ptr-1])) line_ptr--;
		line[line_ptr] = '\0';

		/* if the line end with '\', then continue read the next line */
		if (line[line_ptr-1] == '\\') {
			line_ptr--;
			line[line_ptr] = '\0';
			continue;
		}

		break;
	}
}

/* engine_options can be data_path or engine options. */
int open_engine(locale_id, locale_name, engine_name, engine_path, engine_options)
int 	locale_id;
char 	*locale_name;
char 	*engine_name;
char 	*engine_path;
char 	*engine_options;
{
     	int    		ret, i;
     	char   		file_name[256];
	char 		data_path[256];
     	struct stat 	file_buffer;

     	void   		*so_handler;
     	IMEMethods	methods;

	int 		is_codetable_engine = 0;

     	if (gEngine_Num > MAX_ENGINE_NUM) return (-1);
    
     	/* read profile from file to memory buffer  */ 
	if (*engine_path) {
		if (engine_path[0] != '/') 
			sprintf(file_name, "%s/%s/%s",  DEFAULT_ENGINE_PATH, 
							XAUX_LOCALE_NAME, 
							engine_path);
		else
			sprintf(file_name, "%s", engine_path);
	} else {
		is_codetable_engine = 1;
     		sprintf(file_name, "%s/%s/%s/%s.so", DEFAULT_ENGINE_PATH, 
						     XAUX_LOCALE_NAME, 
						     locale_name, 
						     engine_name);
	}

     	if ((stat(file_name, &file_buffer)) == -1)
     	{ 
		if (is_codetable_engine) {
       			sprintf(file_name, "%s/%s/%s/%s.so", DEFAULT_ENGINE_PATH, 
							     XAUX_LOCALE_NAME, 
							     COMMON_ENGINE_PATH, 
							     CODETABLE_ENGINE_NAME);
        		if ((stat(file_name, &file_buffer)) == -1)
               			return (-1);
     		} else {
			return (-1);
		}
	}
	DEBUG_printf("so_file_name:%s\n", file_name);

     	so_handler = (void *) dlopen(file_name, RTLD_LAZY);
     	if (!so_handler) {
           	printf("can not open so file: %s\n", file_name);
           	return (-1);
     	} else {
           	methods = (IMEMethods) dlsym(so_handler, "ime_methods");
           	if (!methods) {
                	printf("can not open method tables of file:%s\n", file_name);
                	dlclose(so_handler);
                	return(-1);
           	}
     	}

	gEngine_Info[gEngine_Num] = (IMEEngineRec *)calloc(1, sizeof(IMEEngineRec));
	if (gEngine_Info[gEngine_Num] == NULL) return(0);

     	gEngine_Info[gEngine_Num]->core.baseinfo.engine_id = gEngine_Num;
     	gEngine_Info[gEngine_Num]->core.baseinfo.locale_id = locale_id;
     	gEngine_Info[gEngine_Num]->core.baseinfo.status = ENGINE_NOT_INITIATED;
     	gEngine_Info[gEngine_Num]->core.baseinfo.ename = (char *)strdup(engine_name);
     	gEngine_Info[gEngine_Num]->core.baseinfo.cname = NULL;

     	gEngine_Info[gEngine_Num]->core.envinfo.lang_name = (char *)strdup(XAUX_LOCALE_NAME);
     	gEngine_Info[gEngine_Num]->core.envinfo.locale_name = (char *)strdup(locale_name);
     	gEngine_Info[gEngine_Num]->core.envinfo.data_path = NULL;
     	gEngine_Info[gEngine_Num]->core.envinfo.data_ptr = NULL;

	gEngine_Info[gEngine_Num]->core.keymapinfo.bSet = 0;
	for (i=0; i<MAX_KEYMAP_KEY_NUM; i++) 
		gEngine_Info[gEngine_Num]->core.keymapinfo.keymap[i] = NULL;

     	gEngine_Info[gEngine_Num]->so_handler = so_handler;
     	gEngine_Info[gEngine_Num]->so_methods = methods;

	/* IME_SetValues: set the arguments of this IME */
	ret = methods->IME_SetOptions(&(gEngine_Info[gEngine_Num]->core), engine_options);
     	if (ret == -1) {
         	printf("Not successfully set options of the input method engine:%s\n",engine_name);
         	dlclose(so_handler);
         	return(-1);
     	}

	/* IME_Init: get the status, cname, encode information of this Input Method engine */
	ret = methods->IME_Init(&(gEngine_Info[gEngine_Num]->core));
     	if (ret == -1) {
         	printf("Not successfully initialize the input method engine:%s\n",engine_name);
         	dlclose(so_handler);
         	return(-1);
     	}

     	gEngine_Num ++;
	return(0);
}

void hzinput_done()
{
     	int i;
	char *name;

     	for(i=0; i<gEngine_Num; i++) {
		name = gEngine_Info[i]->core.baseinfo.ename;
		if (name) free(name);

		name = gEngine_Info[i]->core.envinfo.lang_name;
		if (name) free(name);

		name = gEngine_Info[i]->core.envinfo.locale_name;
		if (name) free(name);

	 	gEngine_Info[i]->so_methods->IME_Close(&(gEngine_Info[i]->core));
         	dlclose(gEngine_Info[i]->so_handler);
		free((char *)gEngine_Info[i]);
		gEngine_Info[i] = 0;
     	}
     	gEngine_Num = 0;
}
