#include <stdio.h>

#include "le_info.h"

#define LE_CONFIG_FILE            "thai_keymap.cfg"

LeResult le_info_destroy(LeInfoRec * le_info);
LeResult le_info_load_config_file(LeInfoRec * le_info,
				  char *le_config_file);

LeInfoRec *le_info_new()
{
    LeResult result;

    LeInfoRec *le_info = NULL;
    char *le_config_file = LE_CONFIG_FILE;

    le_info = (LeInfoRec *) calloc(1, sizeof(LeInfoRec));
    if (le_info == NULL)
	return (NULL);

    le_info->keymap_list = NULL;

    result = le_info_load_config_file(le_info, le_config_file);
    if (result == LE_FAIL) {
        le_info_destroy(le_info);
        return (NULL);
    }

    return (le_info);
}

LeResult le_info_destroy(LeInfoRec * le_info)
{
    int i;

    if (le_info == NULL)
	return (LE_FAIL);

    /* free keymapping list */
    if (le_info->keymap_list) {
	ThaiKeymapList_Free(le_info->keymap_list);
	free ((char *)le_info->keymap_list);
    }

    free((char *) le_info);

    return (LE_OK);
}

LeResult le_info_print(LeInfoRec * le_info)
{
#ifdef DEBUG
    if (le_info == NULL)
	return (LE_FAIL);

    /* print ime modules */
    if (le_info->keymap_list) {
	ThaiKeymapList_Print(le_info->keymap_list);
    }

    return (LE_OK);
#endif
}

char *le_info_get_full_file_path(char *file_path)
{
    int len;
    char *full_file_path = NULL;

    if (!file_path || !*file_path)
	return (NULL);

    if (file_path[0] == '/') {
	len = strlen(file_path);

	full_file_path = (char *) calloc(len + 1, sizeof(char));
	if (full_file_path == NULL)
	    return (NULL);

	sprintf(full_file_path, "%s", file_path);
    } else {
	len = strlen(LE_BASE_DIR) + 1 + strlen(file_path);

	full_file_path = (char *) calloc(len + 1, sizeof(char));
	if (full_file_path == NULL)
	    return (NULL);

	sprintf(full_file_path, "%s/%s", LE_BASE_DIR, file_path);
    }

    return (full_file_path);
}

LeResult le_info_load_config_file(LeInfoRec * le_info,
				  char *le_config_file)
{
    char *le_config_file_with_full_path = NULL;

    if (le_info == NULL)
	return (LE_FAIL);

    le_config_file_with_full_path =
	(char *) le_info_get_full_file_path(le_config_file);
    if (!le_config_file_with_full_path || !*le_config_file_with_full_path)
	return (LE_FAIL);

    le_info->keymap_list = (TThaiKeymapList *) calloc(1, sizeof(TThaiKeymapList));
    if (le_info->keymap_list == NULL) {
        free((char *) le_config_file_with_full_path);
	return (LE_FAIL);
    }

    /* Get all Thai Keyboard mappings */
    ThaiKeymapList_Init(le_info->keymap_list);
    Thai_Read_Config(le_config_file_with_full_path, le_info->keymap_list);

    free((char *) le_config_file_with_full_path);

    return (LE_OK);
}
