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

#include "unit_input.h"
#include "codetable.h"
#include "ctim.h"
#include "logf.h"

int  ctim_SetOptions(IMECore, char *);
int  ctim_SetValues(IMECore, IMEArgList, int);
int  ctim_Init(IMECore);
int  ctim_Open(IMECore, IMEBuffer, void *);
int  ctim_Filter(IMECore, IMEKey, IMEArgList, IMEBuffer);
void ctim_Close(IMECore);

extern int codetable_filter(CodeTableStruct *hztbl, IMEKey key_event, IMEBufferRec *ime_buffer);

#ifdef	WIN32
#define EXPORT extern __declspec(dllexport)
EXPORT
#endif

/* IF Method */
IMEMethodsRec ime_methods = {
  ctim_SetOptions,
  ctim_SetValues,
  ctim_Init,
  ctim_Open,
  ctim_Filter,
  ctim_Close
};

#define SUFFIX_DICT_FILE	".data"

/* Set options for codetable input method. */
int ctim_SetOptions(IMECore core, char *options)
{
  char 	data_path[256];

  sprintf(data_path, "%s/%s/%s/%s/%s%s", DEFAULT_ENGINE_PATH, core->envinfo.lang_name, options, DEFAULT_DICT_PATH, core->baseinfo.ename, SUFFIX_DICT_FILE);
  core->envinfo.data_path = (char *)strdup(data_path);

  log_f("data_path :%s\n", core->envinfo.data_path);
  return (0);
}

int ctim_SetValues(IMECore core, IMEArgList arglist, int option_value)
{
  int i;

  log_f("ctim_SetValues === \n");

  if (arglist == NULL) return(-1);

  arglist->args_num = 0;

  if (option_value == -1) {
    int  		ret;
    char		*file_name;
    CodeTableStruct ctHeader;

    /* read table from file to memory buffer  */
    file_name = core->envinfo.data_path;
    log_f("LoadCodeTableHeader: file_name:%s\n", file_name);
    ret = LoadCodeTableHeader(file_name, &ctHeader); 
    if (ret != -1) {
      i = KEYBYKEY_MODE_ID;
      arglist->args[i].value = ctHeader.nKeyByKeyMode;
      i = HELPINFO_MODE_ID;
      arglist->args[i].value = ctHeader.nHelpInfoMode;
      i = AUTOSELECT_MODE_ID;
      arglist->args[i].value = ctHeader.nAutoSelectMode;
      i = KEYPROMPT_MODE_ID;
      arglist->args[i].value = ctHeader.nKeyPromptMode;
    }

  } else {
    for (i = 0; i < CTIM_ARGS_NUM; i++) {
      arglist->args[i].value = (option_value >> i) & 1;	
    }
  }

  return(0);
}

/* return the name and encode status and status of codetable IME */
int ctim_Init(IMECore core)
{
  int  		i, ret;
  char		*file_name;
  CodeTableStruct ctHeader;

  log_f("ctim_Init ====\n");

  /* read table from file to memory buffer  */
  file_name = core->envinfo.data_path;
  log_f("file name :%s\n",file_name);

  ret = LoadCodeTableHeader(file_name, &ctHeader); 
  if (ret == -1) 
    return (-1);

  /* Return Information that needed by Input Method Manager */
  /* Such as Encode, Cname, Status */
  core->baseinfo.status = ENGINE_NOT_INITIATED;
  core->baseinfo.lname = (char *)strdup(ctHeader.Lname);
  core->baseinfo.cname = (char *)strdup(ctHeader.Cname);
  core->baseinfo.encode_id = ctHeader.Encode;
	
  core->argsinfo.args_num = CTIM_ARGS_NUM;
  i = KEYBYKEY_MODE_ID;
  core->argsinfo.args[i].name = NULL;
  core->argsinfo.args[i].value = ctHeader.nKeyByKeyMode;
  i = HELPINFO_MODE_ID;
  core->argsinfo.args[i].name = NULL;
  core->argsinfo.args[i].value = ctHeader.nHelpInfoMode;
  i = AUTOSELECT_MODE_ID;
  core->argsinfo.args[i].name = NULL;
  core->argsinfo.args[i].value = ctHeader.nAutoSelectMode;
  i = KEYPROMPT_MODE_ID;
  core->argsinfo.args[i].name = NULL;
  core->argsinfo.args[i].value = ctHeader.nKeyPromptMode;

  return(0);
}


/* Load the codetable file int memory */
int ctim_Open(IMECore core, IMEBuffer ime_buffer, void *handler)
{
  char		*file_name;
  int		i, ret;

  CodeTableStruct *ctHeader;

  log_f("ctim_Open ==== \n");

  ime_buffer->encode = 0;
  ime_buffer->return_status = 0;
  /* 
     ime_buffer->preedit_len = 0;
     ime_buffer->inputkey_len  = 0;
  */
  ime_buffer->commit_len  = 0;
  ime_buffer->lookup_num  = 0;
  ime_buffer->cur_lookup_pos = 0;

  if (core->baseinfo.status == ENGINE_NOT_INSTALLED)
    return(-1);

  if (core->baseinfo.status == ENGINE_INITIATED)
    return 0;

  /* if IME engine is not initiated, would malloc dictionary buffer */

  core->baseinfo.status = ENGINE_NOT_INSTALLED;

  /* read table from file to memory buffer  */
  file_name = core->envinfo.data_path;
  log_f("file name :%s\n",file_name);

  ctHeader = (CodeTableStruct *)calloc(1, sizeof(CodeTableStruct));
  if (ctHeader == NULL) {
    fprintf(stderr, "no memory for CodeTable Input method: %s\n",core->baseinfo.ename);
    return(-1);
  }

  ret = LoadCodeTable(file_name, ctHeader); 
  if (ret == -1) {
    UnloadCodeTable(ctHeader);
    free((char *)ctHeader);
    return(-1);
  }

  core->baseinfo.status = ENGINE_INITIATED;
  core->envinfo.data_ptr = (char *)ctHeader;

  /* if exist keymap setting */
  if (GETBIT(ctHeader->bSectionsFlag, KEYPROMPT_SECTION)) {
    core->keymapinfo.bSet = 1;
    for (i=0; i<MAX_KEYMAP_KEY_NUM; i++) {
      core->keymapinfo.keymap[i] = (char *) strdup(ctHeader->keyprompt[i+0x20].prompt);
      /*
	log_f("keymap: %d\t%s\n", i, core->keymapinfo.keymap[i]);
      */
    }
  }

  return(0);
}

/* close IME, and free codetable pointers */
void ctim_Close(IMECore core)
{
  CodeTableStruct *ctHeader;
  int		i;

  log_f("ctim_Close ==== \n");

  ctHeader = (CodeTableStruct *)(core->envinfo.data_ptr);
  UnloadCodeTable(ctHeader);
  free((char *)ctHeader);
  if (core->baseinfo.lname)
    free((char *)core->baseinfo.lname);
  if (core->baseinfo.cname)
    free((char *)core->baseinfo.cname);

  if (core->envinfo.data_path)
    free((char *)core->envinfo.data_path);

  if (core->keymapinfo.bSet == 1) {
    for (i=0; i<MAX_KEYMAP_KEY_NUM; i++) {
      if (core->keymapinfo.keymap[i])
	free((char *)core->keymapinfo.keymap[i]);
    }
  }
}

/* process key input event */
/* 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  ctim_Filter(core, key_event, ime_args, ime_buffer)
  IMECore core;
IMEKey  key_event;
IMEArgList ime_args;
IMEBuffer ime_buffer;
{
  int 		ret;
  CodeTableStruct *ctHeader;

  log_f("ctim_Filter ==== \n");

  if (core->baseinfo.status != ENGINE_INITIATED)
    return(IME_NOT_USED_KEY);
		
  /* set ctHeader's argument setting */
	
  /* ctHeader's argument setting are always coveried by user defined data */
  ctHeader = (CodeTableStruct *)(core->envinfo.data_ptr);
  ctHeader->Output_Encode = core->envinfo.output_encode_id;

  /* if no user defined arguments, set with system arguments */
  ctHeader->nKeyByKeyMode = core->argsinfo.args[KEYBYKEY_MODE_ID].value;
  ctHeader->nHelpInfoMode = core->argsinfo.args[HELPINFO_MODE_ID].value;
  ctHeader->nAutoSelectMode = core->argsinfo.args[AUTOSELECT_MODE_ID].value;
  ctHeader->nKeyPromptMode = core->argsinfo.args[KEYPROMPT_MODE_ID].value;

  if (ime_args != NULL && ime_args->args_num > 0) {
    /* if has user defined arguments, set with user defined arguments */
    ctHeader->nKeyByKeyMode = ime_args->args[KEYBYKEY_MODE_ID].value;
    ctHeader->nHelpInfoMode = ime_args->args[HELPINFO_MODE_ID].value;
    ctHeader->nAutoSelectMode = ime_args->args[AUTOSELECT_MODE_ID].value;
    ctHeader->nKeyPromptMode = ime_args->args[KEYPROMPT_MODE_ID].value;
  }
		
  if (!strncmp(core->baseinfo.cname,(char *)"Latin", strlen(core->baseinfo.cname))) {
    if ((key_event->keyCode == IM_VK_F9) && (!key_event->keyChar) && (!key_event->modifier)) {
      log_f("HOTKEY for COMPOSE_KEY is pressed \n");
      key_event->keyCode = IM_VK_T;
      key_event->keyChar = IM_VK_T;
      key_event->modifier = IM_CTRL_MASK|IM_SHIFT_MASK ;
    }
  }
  ret = codetable_filter(ctHeader, key_event, ime_buffer);
  log_f("codetable_filter : return: %d\n", ret);

  /*  TODO!! Disabling Lookup window Should be done using configuration file */
  if (((!strncmp(core->baseinfo.cname,(char *)"Latin", strlen(core->baseinfo.cname))) && (ime_buffer->return_status & IME_LOOKUP_AREA)) || ((!strncmp(core->envinfo.locale_name,(char *)"am_ET", strlen(core->envinfo.locale_name))) && (ime_buffer->return_status & IME_LOOKUP_AREA)) || ((!strncmp(core->envinfo.locale_name,(char *)"ti_ER", strlen(core->envinfo.locale_name))) && (ime_buffer->return_status & IME_LOOKUP_AREA))) {
    ime_buffer->return_status &= ~IME_LOOKUP_AREA;
  }

  return(ret);
}

