/*
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 "zhuyin_data.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define MAX_LINE_LEN    256

#define BASE_DIR_STRING         "base_dir"
#define DATA_FILE_STRING        "data_file"
#define KEYMAP_STRING           "keymap"

#define BASE_DIR_NAME_STRING    "path"
#define DATA_FILE_NAME_STRING   "file"
#define KEYMAP_NAME_STRING      "name"

enum {
	ZHUYIN_DEFAULT_SECTION = 0,
	ZHUYIN_BASE_DIR_SECTION,
	ZHUYIN_DATA_FILE_SECTION,
	ZHUYIN_KEYMAP_SECTION,
};

/**************************************************************
The format of Zhuyin configure file as follow:

[base_dir]
path=/usr/lib/iiim/le/twle/input_methods

[data_file]
file=data/zhuyin.data

[keymap name="ZhuyinKeymapName"]
ZhuyinSymbol  ZhuyinKey

**************************************************************/

int parse_line_for_keymap_name(TZhuyinData *pZhuyinData, char *line_buf);

char *skip_space(char *s)
{
        while (*s && (*s == ' ' || *s == '\t')) s++;
        return s;
}

char *to_space(char *s)
{
	while (*s && !(*s == ' ' || *s == '\t')) s++;
        return s;
}

char *trim_string(char *s)
{
	char *head_ptr, *tail_ptr;

	if (!s || !*s) return(s);

	head_ptr = s;

	/* trim left space */
	while(*head_ptr && (*head_ptr == ' ' || *head_ptr == '\t' || *head_ptr == '\n'))
		head_ptr ++;

	if (!*head_ptr) return(head_ptr);

	/* trim right space */
	tail_ptr = head_ptr + strlen(head_ptr) - 1;
	
	while(*tail_ptr && (*tail_ptr == ' ' || *tail_ptr == '\t' || *tail_ptr == '\n')) {
		*tail_ptr = '\0';
		tail_ptr --;
	}

	return(head_ptr);
}

int parse_line_for_pair(char *line_buf, char **key_ptr, char **value_ptr)
{
	char *ptr, *kptr, *vptr;

	*key_ptr = ptr = skip_space(line_buf);

	while(*ptr && !(*ptr==' ' || *ptr=='\t' || *ptr=='\n' || *ptr=='=' || *ptr==':')) ptr++;

	if (*ptr=='=' || *ptr==':') {
		*ptr = '\0';
		ptr = skip_space(ptr+1);
	} else if (*ptr==' ' || *ptr=='\t') {
		*ptr = '\0';
		ptr = skip_space(ptr+1);
		if (*ptr=='=' || *ptr==':') {
			ptr = skip_space(ptr+1);
		}
	} else if (*ptr=='\n') {
		*ptr = '\0';
	}

	/* skip " */
	if (*ptr == '\"') ptr++;
	*value_ptr = ptr;
	
	ptr = to_space(ptr);
	if (*(ptr-1) == '\"') ptr--;
	*ptr = '\0';

	return(0);
}

int parse_line_for_section_flag(TZhuyinData *pZhuyinData, char *line_buf)
{
	char *flag_section_str;

	int flag_section = ZHUYIN_DEFAULT_SECTION;

	/* Extract the name of section */
	line_buf[strlen(line_buf) - 1] = '\0';
	flag_section_str = trim_string(line_buf+1);

	if (!*flag_section_str) return(ZHUYIN_DEFAULT_SECTION);

	/* get flag_section */
	if (!(strncasecmp(flag_section_str, BASE_DIR_STRING, strlen(BASE_DIR_STRING)))) {
		flag_section = ZHUYIN_BASE_DIR_SECTION;
	} else if (!(strncasecmp(flag_section_str, DATA_FILE_STRING, strlen(DATA_FILE_STRING)))) {
		flag_section = ZHUYIN_DATA_FILE_SECTION;
	} else if (!(strncasecmp(flag_section_str, KEYMAP_STRING, strlen(KEYMAP_STRING)))) {
		flag_section = ZHUYIN_KEYMAP_SECTION;
		parse_line_for_keymap_name(pZhuyinData, flag_section_str + strlen(KEYMAP_STRING));
	}

	return(flag_section);
}

int parse_line_for_basedir_section(TZhuyinData *pZhuyinData, char *line_buf, char **pBaseDir)
{
	char *key_ptr, *value_ptr;

	parse_line_for_pair(line_buf, &key_ptr, &value_ptr);

	if (!strcasecmp(key_ptr, BASE_DIR_NAME_STRING)) {
		if (*pBaseDir != NULL) free((char *)*pBaseDir);
		*pBaseDir = (char *)strdup(value_ptr);
	}
	return(ZHUYIN_OK);
}

int parse_line_for_datafile_section(TZhuyinData *pZhuyinData, char *line_buf, char **pDataFile)
{
	char *key_ptr, *value_ptr;

	parse_line_for_pair(line_buf, &key_ptr, &value_ptr);

	if (!strcasecmp(key_ptr, DATA_FILE_NAME_STRING)) {
		if (*pDataFile != NULL) free((char *)*pDataFile);
		*pDataFile = (char *)strdup(value_ptr);
	}
	return(ZHUYIN_OK);
}

int parse_line_for_keymap_section(TZhuyinData *pZhuyinData, char *line_buf)
{
	char *key_ptr, *value_ptr;
	int nKeymap_ID;

	parse_line_for_pair(line_buf, &key_ptr, &value_ptr);

	nKeymap_ID = pZhuyinData->pZhuyinKeymapList->nNum_Keymaps - 1;
	ZhuyinKeymapList_Item_Set_KeymapValue(pZhuyinData->pZhuyinKeymapList, nKeymap_ID, key_ptr, *value_ptr);

	return(ZHUYIN_OK);
}

int parse_line_for_keymap_name(TZhuyinData *pZhuyinData, char *line_buf)
{
	char *key_ptr, *value_ptr;
	int nKeymap_ID;

	if (pZhuyinData->pZhuyinKeymapList->nNum_Keymaps == 0) {
		pZhuyinData->pZhuyinKeymapList->nNum_Keymaps++;
		ZhuyinKeymapList_Item_Prepare(pZhuyinData->pZhuyinKeymapList, 0);
		ZhuyinKeymapList_Item_Add_StandardKeymap(pZhuyinData->pZhuyinKeymapList, 0);
	}

	nKeymap_ID = pZhuyinData->pZhuyinKeymapList->nNum_Keymaps - 1;
	if (pZhuyinData->pZhuyinKeymapList->pKeymaps[nKeymap_ID]->pName != NULL)
		pZhuyinData->pZhuyinKeymapList->nNum_Keymaps ++;

	nKeymap_ID = pZhuyinData->pZhuyinKeymapList->nNum_Keymaps - 1;
	ZhuyinKeymapList_Item_Prepare(pZhuyinData->pZhuyinKeymapList, nKeymap_ID);

	parse_line_for_pair(line_buf, &key_ptr, &value_ptr);
	if (!strcasecmp(key_ptr, KEYMAP_NAME_STRING)) {
		ZhuyinKeymapList_Item_Set_Name(pZhuyinData->pZhuyinKeymapList, nKeymap_ID, value_ptr);
	}
}

ZhuyinData_Read_Config(char *file_name, TZhuyinData *pZhuyinData)
{
	FILE *ifile;
	char line_buf[MAX_LINE_LEN], *line_ptr;
	int flag_section;
	char *pBaseDir = NULL;
	char *pDataFile = NULL;
	char *data_base_dir, *data_file_name;
	char data_file_path[MAX_LINE_LEN];

	ifile = fopen(file_name, "r");
	if (ifile == NULL) {
		fprintf(stderr, "Error: open file %s\n", file_name);
		return(ZHUYIN_ERROR);
	}

	while(fgets(line_buf, MAX_LINE_LEN, ifile) != NULL) {
		line_ptr = trim_string(line_buf);

		if (*line_ptr && line_ptr[0] == '[' && line_ptr[strlen(line_ptr)-1] == ']') {
			flag_section = parse_line_for_section_flag(pZhuyinData, line_ptr);
			continue;
		}

		/* If space line or comment line */
		if (*line_ptr == '\0' || *line_ptr == '#') continue;

		switch (flag_section) {
			case ZHUYIN_DEFAULT_SECTION:
				break;

			case ZHUYIN_BASE_DIR_SECTION:
				parse_line_for_basedir_section(pZhuyinData, line_ptr, &pBaseDir);
				break;

			case ZHUYIN_DATA_FILE_SECTION:
				parse_line_for_datafile_section(pZhuyinData, line_ptr, &pDataFile);
				break;

			case ZHUYIN_KEYMAP_SECTION:
				parse_line_for_keymap_section(pZhuyinData, line_ptr);
				break;
		}
	}

	pZhuyinData->data_file = NULL;

	if (pBaseDir)
		data_base_dir = pBaseDir;
	else
		data_base_dir = LE_IME_MODULES_DIR;

	if (pDataFile)
		data_file_name = pDataFile;
	else
		data_file_name = "data/zhuyin.data";

	snprintf(data_file_path, MAX_LINE_LEN, "%s/%s", data_base_dir, data_file_name);
	pZhuyinData->data_file = (char *)strdup(data_file_path);

	if (pBaseDir) free((char *)pBaseDir);
	if (pDataFile) free((char *)pDataFile);

	fclose(ifile);

	return(ZHUYIN_OK);
}
