/*
  Copyright 2002-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 <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "le.h"
#include "encode.h"
#include "xaux_locale.h"

Bool if_le_OpenIF(iml_if_t *);
Bool if_le_CloseIF(iml_if_t *);
Bool if_le_GetIFValue(iml_if_t *, IMArgList, int);
Bool if_le_SetIFValue(iml_if_t *, IMArgList, int);
Bool if_le_OpenDesktop(iml_desktop_t *, IMArgList, int);
Bool if_le_CloseDesktop(iml_desktop_t *);
Bool if_le_CreateSC(iml_session_t *, IMArgList, int);
Bool if_le_DestroySC(iml_session_t *);
Bool if_le_GetSCValue(iml_session_t *, IMArgList, int);
Bool if_le_SetSCValue(iml_session_t *, IMArgList, int);
IMText *if_le_ResetSC(iml_session_t *);
void if_le_SetSCFocus(iml_session_t *);
void if_le_UnsetSCFocus(iml_session_t *);
void if_le_SendEvent(iml_session_t *, IMInputEvent * ev);
int get_list_of_supported_locales();
unit_desktop_t *create_unit_desktop();
void add_unit_desktop(unit_desktop_t *udp);
unit_desktop_t * find_unit_desktop_by_sc(iml_session_t *);

/* IF Method */
if_methods_t le_methods = {
	if_le_OpenIF,
	if_le_CloseIF,
	if_le_GetIFValue,
	if_le_SetIFValue,
	if_le_OpenDesktop,
	if_le_CloseDesktop,
	if_le_CreateSC,
	if_le_DestroySC,
	if_le_GetSCValue,
	if_le_SetSCValue,
	if_le_ResetSC,
	if_le_SetSCFocus,
	if_le_UnsetSCFocus,
	if_le_SendEvent
};

extern char lename_string[];
extern UTFCHAR lename_utf_string[];
extern char default_locale_id;
extern void get_line(char *buf, int size, char **curptr, char *line);
extern void unit_desktop_init(unit_desktop_t *udp);
extern int unit_desktop_add_listener(unit_desktop_t *udp, iml_session_t *s);
extern void unit_desktop_done(unit_desktop_t *udp);

extern IMEBufferRec *ime_buffer_malloc();
extern void ime_buffer_free(IMEBuffer);
extern void le_status_draw(unit_desktop_t *, iml_session_t *);
extern void proc_key_event(unit_desktop_t *, iml_session_t *, IMKeyListEvent *);
extern int get_encodeid_from_locale(char *);
extern void proc_key_switch_conversion_event(unit_desktop_t *, iml_session_t *, int, char *);

static IMLEName lename = {lename_string, lename_utf_string };
static IMObjectDescriptorStruct *objects = NULL;
IMLocale locales[MAX_SUPPORTED_LOCALES];
int n_Supported_Locales;
unit_if_t *UIf;

/* htt_server get the IF information when start htt_server */
void 
if_GetIfInfo( IMArgList args, int num_args)
{
    int i;

    printf("if_GetIfInfo == num_args:%d\n", num_args);

    n_Supported_Locales =  get_list_of_supported_locales();
    printf("n_Supported_Locales [%d]\n",n_Supported_Locales);

    for (i = 0; i < num_args; i++, args++) {
	switch (args->id) {
	  case IF_VERSION:
	   args->value = (IMArgVal) "1.2";
	   break;
	  case IF_METHOD_TABLE:
	   args->value = (IMArgVal) & le_methods;
	   break;
	  case IF_LE_NAME:
	   args->value = (IMArgVal) & lename;
	   break;
	  case IF_SUPPORTED_LOCALES:
	   args->value = (IMArgVal) & locales;
	   break;
	  case IF_SUPPORTED_OBJECTS:
	   args->value = (IMArgVal) objects; 
	   break;
	  case IF_NEED_THREAD_LOCK:
	   args->value = (IMArgVal) True;
	   break;
	  default:
	   break;
	}
    }
}

/* Open the IF interface */
Bool 
if_le_OpenIF(iml_if_t * If)
{
    printf("if_le_OpenIF ====\n");

    UIf = 0;

    return True;
}

/* Close the IF interface */
Bool 
if_le_CloseIF(iml_if_t * If)
{
    int i;

    printf("if_le_CloseIF === \n");

    for (i=0 ; i<n_Supported_Locales ; i++){
	if (locales[i].id != NULL) {
	    free(locales[i].id);
	    locales[i].id = NULL;
	}
	if (locales[i].name != NULL) {
	    free(locales[i].name);
	    locales[i].name = NULL;
	}
    }

    if (UIf)
	free(UIf);

    return True;
}

Bool 
if_le_GetIFValue(iml_if_t * If, IMArgList args, int num_args)
{
    printf("if_le_GetIFValue()\n");
    return True;
}

Bool 
if_le_SetIFValue(iml_if_t * If, IMArgList args, int num_args)
{
    printf("if_le_SetIFValue()\n");
    return True;
}

unit_if_t *
unit_if() {
    if (!UIf) {
	UIf = (unit_if_t *)calloc(1, sizeof(unit_if_t));
	UIf->create_unit_desktop = create_unit_desktop;
	UIf->add_unit_desktop = add_unit_desktop;
	UIf->find_unit_desktop_by_sc = find_unit_desktop_by_sc;
	UIf->ud_count = 0;
    } 
    if (!UIf) 
	printf("calloc/realloc error in unit_if() \n");

    return UIf;
}

unit_desktop_t *
create_unit_desktop() {
    unit_desktop_t *udp = (unit_desktop_t *) calloc(1, sizeof(unit_desktop_t));
    udp->next = unit_if()->ud_list;
    return udp;
}

void 
add_unit_desktop(
    unit_desktop_t *udp
) 
{
    udp->unit_desktop_init = unit_desktop_init;
    udp->unit_desktop_add_listener = unit_desktop_add_listener;
    udp->unit_desktop_done = unit_desktop_done;
    unit_if()->ud_list = udp;
    unit_if()->ud_count++;
    return;
}

unit_desktop_t *
find_unit_desktop_by_sc(iml_session_t *s) {
    unit_desktop_list udl, *prev;

    if (UIf->ud_list == NULL) {
	return (unit_desktop_t *) NULL; 
    }
    for (prev = &UIf->ud_list; (udl = *prev) != 0; prev = &udl->next) {
        if (udl->s) {
	    if (udl->s->desktop == s->desktop)
		return udl;
        } else if ((udl->s == 0) && (udl->next == NULL)) {
	    return udl;
	}
    }
    return (unit_desktop_t *) NULL; 
}

Bool 
if_le_OpenDesktop(iml_desktop_t * desktop, IMArgList args, int num_args)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)calloc(1,sizeof(MyDataPerDesktop));
    unit_desktop_t *udp = (unit_desktop_t *) 0;

    udp = unit_if()->create_unit_desktop();
    unit_if()->add_unit_desktop(udp);
    udp->unit_desktop_init(udp); 
    printf("if_le_OpenDesktop: udp [0x%x]\n", udp);

    desktop_data->current_session = 0;
    desktop_data->root_session = 0;
    desktop_data->aux_locale_id = default_locale_id;
    desktop_data->udp = udp;

    desktop->specific_data = (void *) desktop_data;


    return True;
}

Bool 
if_le_CloseDesktop(iml_desktop_t * desktop)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *) desktop->specific_data;
    unit_desktop_t *temp, *prev;
    int i;

    printf("if_le_CloseDesktop: udp [0x%x] \n", desktop_data->udp);
    for (i=0; i<MAX_ENGINE_NUM; i++) {
	if (desktop_data->ime_args[i] != (IMEArgList) NULL)
	    free((char *)desktop_data->ime_args[i]);
    }
    if (UIf && (UIf->ud_count > 0)) {
	temp = desktop_data->udp;
	prev = UIf->ud_list; /* Starting of the node */
	if ((temp == prev) && (temp->next == NULL)) {
	    unit_desktop_done(temp);
	    UIf->ud_count--;
	    free(temp);
	} else {
	    while ((prev->next != temp) && (prev->next != NULL)) {
		prev = prev->next;
	    }
	    prev->next = temp->next;
	    if (temp->next == NULL)
		temp->next = prev;
	    unit_desktop_done(temp);
	    UIf->ud_count--;
	    free(temp);
	}
    }
    free(desktop_data);
    return True;
}

Bool 
if_le_CreateSC(iml_session_t *s, IMArgList args, int num_args)
{
    int i;
    iml_desktop_t *desktop = s->desktop;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *) desktop->specific_data;
    unit_desktop_t *udp = desktop_data->udp;
    MyDataPerSession *p = (MyDataPerSession *) calloc(1, sizeof(MyDataPerSession));
    printf("if_le_CreateSC: udp [0x%x] \n", desktop_data->udp);

    desktop_data->current_session = 0;
    p->paletteaux_status.engine_id = 0xff;
    desktop_data->udp->s = 0;
    
    /* Allocate memory for input method session context */
    p->ime_buffer = (IMEBuffer)ime_buffer_malloc();
    p->locale = NULL;

    s->specific_data = (void*) p;

    /* set aux proxy data */
    p->protocol_type = UNKNOWN_IMP;
    p->client_type = UNKNOWN_CLIENT;
    for (i = 0; i < num_args; i++, args++) {
	switch (args->id) {
	  case UI_PROTOCOL_TYPE:
	   if (args->value) {
	       printf("UI_PROTOCOL_TYPE: value: %s\n", args->value);
	       if (!strcmp (UI_PROTOCOL_TYPE_XIMP, args->value))
		   p->protocol_type = XIMP;
	   }
	   break;
	  case UI_CLIENT_TYPE:
	   if (args->value) {
	       printf("UI_CLIENT_TYPE: value: %s\n", args->value);
	       if (!strcmp (UI_CLIENT_TYPE_X, args->value))
		   p->client_type = X11_CLIENT;
	   }
	   break;
	}
    }
    if (p->protocol_type == XIMP && p->client_type == X11_CLIENT)
	if (desktop_data->root_session == 0)
	    desktop_data->root_session = s;

    return True;
}

Bool 
if_le_DestroySC(iml_session_t * s)
{
    iml_desktop_t *desktop = s->desktop;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *) desktop->specific_data;
    MyDataPerSession *p = (MyDataPerSession *) s->specific_data;

    printf("if_le_DestroySC: udp [0x%x] \n", desktop_data->udp);

    desktop_data->current_session = 0;
    desktop_data->udp->s = 0;

    if (p->locale != NULL) {
	free((char *)p->locale);
	p->locale = NULL;
    }

    ime_buffer_free(p->ime_buffer);
    free((char *) p);

    if (s == desktop_data->root_session)
	desktop_data->root_session = 0;

    return True;
}

Bool 
if_le_GetSCValue(iml_session_t * s, IMArgList args, int num_args)
{
    printf("if_le_GetSCValue(s=%x)\n\n", s);
    return True;
}

Bool 
if_le_SetSCValue(iml_session_t * s, IMArgList args, int num_args)
{
    int i;
    IMArg *p = args;
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    MyDataPerSession *session_data = (MyDataPerSession *) s->specific_data;
    unit_desktop_t *udp = desktop_data->udp;

    printf("if_le_DestroySC: udp [0x%x]\n", desktop_data->udp);
    /*
      printf("if_le_SetSCValue(), desktop:0x%x\n", s->desktop);
      printf("if_le_SetSCValue(), s:0x%x\n", s);
      printf("if_le_SetSCValue(), udp->s:0x%x\n", udp->s);
    */

    desktop_data->current_session = s;
    desktop_data->udp->s = s;

    for (i = 0; i < num_args; i++, p++) {
	switch (p->id) {
	  case SC_CLIENT_LOCALE:
	   printf("if_le_SetSCValue(): SC_CLIENT_LOCALE: [%s]\n",p->value);
	   if (session_data->locale != NULL) {
	       free((char *)session_data->locale);
	       session_data->locale = NULL;
	   }
	   session_data->locale = (char *)strdup(p->value);
	   break;
	  case SC_TRIGGER_ON_NOTIFY:
	   proc_key_switch_conversion_event(udp, s, CONVERSION_ON, (char *)session_data->locale);
	   break;
                
	  case SC_TRIGGER_OFF_NOTIFY:
	   printf("SC_TRIGGER_OFF_NOTIFY\n");
	   proc_key_switch_conversion_event(udp, s, CONVERSION_OFF, (char *)NULL);
	   break;
                
	  case SC_REALIZE:
	   printf("SC_REALIZE, root_session:0x%x\n", desktop_data->root_session);
           if (s->desktop->session_count == 1) {
	       printf("if_le_CreateSC() : Loading Engines ...\n");
	       udp = unit_if()->ud_list;
	       udp->unit_desktop_add_listener(udp, s); 
           } 
	   le_status_draw(udp, s);
	   break;

	  default:
	   break;
	}
    }
  
    return True;
}

IMText *
if_le_ResetSC(iml_session_t * s)
{
    printf("if_le_ResetSC(s=%x)\n\n", s);
    return (IMText *) NULL;
}

void 
if_le_SetSCFocus(iml_session_t * s)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    unit_desktop_t *udp = desktop_data->udp;

    printf("if_le_SetSCFocus() s:%x, current_session:%x, udp:0x%x\n", s, desktop_data->current_session, desktop_data->udp);

    desktop_data->current_session = s;
    desktop_data->udp->s = s;
    le_status_draw(udp, s);
}

void 
if_le_UnsetSCFocus(iml_session_t * s)
{
    printf("if_le_UnsetSCFocus() s:%x\n", s);
}

void 
if_le_SendEvent(iml_session_t * s, IMInputEvent * ev)
{
    MyDataPerDesktop *desktop_data = (MyDataPerDesktop *)(s->desktop->specific_data);
    unit_desktop_t *udp = desktop_data->udp;

    printf("if_le_SendEvent session=%x\n", s);
    if (ev) {
	if (ev->type == IM_EventKeyList) {
	    printf("Keyboard Event\n");
	    proc_key_event(udp, s, (IMKeyListEvent *)ev);
	} 
    }
}

int 
get_list_of_supported_locales(){
    char	file_name[PATH_MAX], line[MAX_LINE_LEN]; 
    char        *file_buf, *curr_ptr;
    char	keyCodeName[NAME_MAX], modifierName[NAME_MAX];
    char	locale_name[NAME_MAX], *kptr, *ptr;
    
    int	len, n, nfread, fsize, fd;
    int	locale_flag = ENCODE_ERROR;
    int	generic_flag = 0;
    int	switch_locale_flag = 0;
    int	switch_layout_flag = 0;
    FILE	*fp;
    struct stat buf;

    n = 0;

    memset((char *)keyCodeName,'\0',sizeof(keyCodeName));
    memset((char *)modifierName,'\0',sizeof(modifierName));

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

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

    fd = fileno((FILE *)fp);
    if (fstat(fd, &buf) < 0) {
        return -1;
    }
    fsize = buf.st_size;
    printf("fsize [%d]\n",fsize);
    file_buf = (char *)calloc(fsize, sizeof(char));
    nfread = fread(file_buf, fsize, 1, fp);
    printf("nfread [%d]\n",nfread);

    curr_ptr = 0;

    do {
        get_line(file_buf, fsize, &curr_ptr, 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++;

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

	    /* get locale section name */
	    if (!strcasecmp(locale_name, COMMON_ENGINE_PATH))
		locale_flag = ENCODES_NUM;
	    else if(!strcasecmp(locale_name, GENERIC_IM_TABLE_NAME)){
		generic_flag = 1;
		continue;
	    }else if(!strcasecmp(locale_name, SWITCH_LOCALE_NAME)){
		switch_locale_flag = 1;
		continue;
	    }else if(!strcasecmp(locale_name, SWITCH_LAYOUT_NAME)){
		switch_layout_flag = 1;
		continue;
	    } 

	    if(!generic_flag)
		locale_flag = get_encodeid_from_locale(locale_name);
	    else{
		locale_flag = ENCODES_NUM;

		locales[n].id = (char *)strdup(locale_name);
		locales[n].name = (UTFCHAR *)calloc(strlen(locale_name)+1,sizeof(UTFCHAR));
		CpyUTFCHAR(locale_name, locales[n].name);
		n++;
	    }
	    continue;
	}else
	    continue;
    } while (1);
    locales[n].id = (char *)NULL;
    locales[n].name = (UTFCHAR *)NULL;
    fclose(fp);
    return(n);
}

int 
CpyUTFCHAR(char *src, UTFCHAR *dest){
    int i;

    for(i=0;*src;i++){
	*dest++ = *src++;
    }
    *dest = 0;
    return i;
}
/* Local Variables: */
/* c-file-style: "iiim-project" */
/* End: */
