/*
Copyright (C) 1990-2001 Sun Microsystems, Inc.
Copyright (C) 2001,2004 Red Hat, Inc.
Copyright (C) 2001,2004 Yukihiro Nakai <nakai@gnome.gr.jp>

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
Red Hat, 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 Red Hat, 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
Red Hat, Inc. or its licensors is granted.

*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <sys/types.h>

#include "SunIM.h"

#include <dlfcn.h>
#include <jllib.h>
#include "csconv.h"

#ifndef BUFSIZE
#define BUFSIZE 1024
#endif

#define WNNRCFILE "/etc/FreeWnn/ja/wnnenvrc"

#define CSC_PATH "/usr/lib/im/csconv/csconv.so"
#define CSC_OPEN_LOCALE "csconv_open_locale"
#define CSC_OPEN        "csconv_open"
#define CSC_CONV        "csconv"
#define CSC_CLOSE       "csconv_close"

#define wnn_printf(a)	printf a

typedef csconv_t        (* csc_open_locale_t)(const char *,
                                              const char *, const char *);
typedef csconv_t        (* csc_open_t)(const char *, const char *);
typedef size_t          (* csc_conv_t)(csconv_t, const char **, size_t *,
                                       char **, size_t *);
typedef int             (* csc_close_t)(csconv_t);

static void *                   csc_handle = NULL;
static csc_open_locale_t        csc_open_locale;
static csc_open_t               csc_open;
static csc_conv_t               csc_conv;
static csc_close_t              csc_close;
static csconv_t                 csconv_cd = NULL;
static csconv_t                 csconv_utf8_cd = NULL;

Bool if_freewnn_OpenIF(iml_if_t *);
Bool if_freewnn_CloseIF(iml_if_t *);
Bool if_freewnn_GetIFValues(iml_if_t *, IMArgList, int);
Bool if_freewnn_SetIFValues(iml_if_t *, IMArgList, int);
Bool if_freewnn_OpenDesktop(iml_desktop_t *, IMArgList, int);
Bool if_freewnn_CloseDesktop(iml_desktop_t *);
Bool if_freewnn_CreateSC(iml_session_t*, IMArgList, int);
Bool if_freewnn_DestroySC(iml_session_t *);
Bool if_freewnn_GetSCValues(iml_session_t *, IMArgList, int);
Bool if_freewnn_SetSCValues(iml_session_t *, IMArgList, int);
IMText *if_freewnn_ResetSC(iml_session_t *);
void if_freewnn_SetSCFocus(iml_session_t *);
void if_freewnn_UnsetSCFocus(iml_session_t *);
void if_freewnn_SendEvent(iml_session_t *, IMInputEvent * ev);

void freewnn_status_draw(iml_session_t *s, char* str);

static if_methods_t if_methods = {
  if_freewnn_OpenIF,
  if_freewnn_CloseIF,
  if_freewnn_GetIFValues,
  if_freewnn_SetIFValues,
  if_freewnn_OpenDesktop,
  if_freewnn_CloseDesktop,
  if_freewnn_CreateSC,
  if_freewnn_DestroySC,
  if_freewnn_GetSCValues,
  if_freewnn_SetSCValues,
  if_freewnn_ResetSC,
  if_freewnn_SetSCFocus,
  if_freewnn_UnsetSCFocus,
  if_freewnn_SendEvent
};

UTFCHAR lename_string[] = {
  0x3046, 0x3093, 0x306C, 0x4C, 0x45, 0x0 /* Wnn LE */
};

UTFCHAR jahrn_string[] = {
  0x65E5, 0x672C, 0x8A9E /* Nihongo */
};

static IMLEName lename = {
    "FreeWnnLE",
    lename_string
};

static IMLocale locales[] = {
    {
        "ja",
        jahrn_string
    },
    {NULL, NULL},
};

#include "convtable.h"

typedef struct {
  Bool conv_on; /* conversion mode is on */
  char* preedit_buf; /* preedit buffer */
  Bool preedit_start; /* preedit window draw started */
  struct wnn_buf* wbuf; /* Wnn Buffer */
  Bool kanji_on; /* Under selecting candidate */
} FreeWnnSession;

FreeWnnSession*
freewnn_session_data(iml_session_t *s) {
  return (FreeWnnSession*)s->specific_data;
}


w_char*
char2wchar(unsigned char* str) {
  w_char* result = NULL;
  int i=0;
  int j=0;
  int count = 0;

  if( str == NULL ) return NULL;
  if( *str == '\0' ) return NULL;

  for(i=0;i<strlen(str);i++) {
    count++;
    if( str[i] & 0x80 )
      i++;
  }

  result = (w_char*)calloc(count+1, sizeof(w_char));
  for(i=0;i<strlen(str);i++) {
    if( str[i] & 0x80 ) {
      result[j] =  str[i];
      result[j] = (result[j] << 8 ) | str[++i];
    } else {
      result[j] = str[i];
    }
    j++;
  }

#if 0
  {
    for(i=0;i<count;i++) {
      printf("0x%04x\n", result[i]);
    }
  }
#endif

  return result;
}

unsigned char*
wchar2char(w_char* wstr) {
  char* result = NULL;
  int i;
  int j;
  int count = 0;

  if( wstr == NULL ) return NULL;

  if( *wstr == 0 ) return NULL;

  for(i=0;wstr[i] != 0;i++) 
    count++;

  result = (unsigned char*)calloc(count*2+1, sizeof(unsigned char));
  j=0;
  for(i=0;i<count;i++) {
    if( wstr[i] & 0xff00 ) {
      result[j++] = wstr[i] >> 8;
    }
    result[j++] = wstr[i] & 0xff;
  }

  return result;
}

void
freewnn_conversion(iml_session_t *s) {
  FreeWnnSession* session_data = freewnn_session_data(s);
  w_char* wcbuf = NULL;
  w_char kanjibuf[BUFSIZE];

  bzero(kanjibuf, sizeof(w_char)*BUFSIZE);

  if( strlen(session_data->preedit_buf) == 0 )
    return;

  if( session_data->kanji_on == False ) {
    wcbuf = char2wchar(session_data->preedit_buf);
    jl_ren_conv(session_data->wbuf, wcbuf, 0, -1, WNN_NO_USE);
    jl_zenkouho(session_data->wbuf, 0, WNN_NO_USE, WNN_UNIQ);
    session_data->kanji_on = True;
  }

  jl_get_kanji(session_data->wbuf, 0, -1, kanjibuf);
  bzero(session_data->preedit_buf, sizeof(char)*BUFSIZE);
  wnn_printf(("%s\n", wchar2char(kanjibuf)));
  strcpy(session_data->preedit_buf, wchar2char(kanjibuf));
  jl_next(session_data->wbuf);
}


void printError(char* s) {
  wnn_printf(("%s\n", s));
}

int printConfirm(char* s) {
  wnn_printf(("%s\n", s));
  return 1;
}

int
strrncmp(char* s1, char* s2, size_t n) {
  char* s1tmp = s1;
  if( strlen(s1) >= n ) {
    s1tmp += strlen(s1)-n;
  }

  return strcmp(s1tmp, s2);
}

char*
roma2kana(char* romastr) {
  char* result = NULL;
  int tsize = sizeof(kanatable)/sizeof(kanatable[0]);
  int i;

  if( romastr == NULL ) return NULL;
  if( *romastr == '\0' ) return NULL;

  for(i=0;i<tsize;i++) {
    romapair rp = kanatable[i];
    if( strrncmp(romastr, rp.roma, strlen(rp.roma)) == 0 ) {
      int len = strlen(romastr)-strlen(rp.roma)+strlen(rp.kana)+1;
      result = (char*)calloc(len+1, sizeof(char));
      strncat(result, romastr, strlen(romastr)-strlen(rp.roma));
      strcat(result, rp.kana);
      return result;
    }
  }

  result = strdup(romastr); /* No change */

  return result;
}

void
buffer_tailcut(char* buf) {
  if( buf == NULL ) return;
  if( *buf == '\0') return;

  if( strlen(buf) == 1 ) {
    buf[strlen(buf)-1] = '\0';
  } else if( buf[strlen(buf)-1] & 0x80 ) {
    buf[strlen(buf)-1] = '\0';
    buf[strlen(buf)-1] = '\0';
  } else
    buf[strlen(buf)-1] = '\0';
}

void
buffer_append(char* buf, char ch) {
  char* kana = NULL;

  if( buf == NULL ) return;

  buf[strlen(buf)] = ch;
  buf[strlen(buf)] = '\0';

  kana = roma2kana(buf);
  strcpy(buf, kana);

  //free(kana);
}

void
freewnn_conversion_on(iml_session_t *s) {
  FreeWnnSession* session_data = freewnn_session_data(s);

  session_data->conv_on = True;
  wnn_printf(("Conversion on\n"));
}

void
freewnn_conversion_off(iml_session_t *s) {
  FreeWnnSession* session_data = freewnn_session_data(s);

  session_data->conv_on = False;
  wnn_printf(("Conversion off\n"));
}

IMFeedbackList *
create_feedback(iml_session_t *s, int size)
{
    int i;
    IMFeedbackList *feedback, *fbl;
    IMFeedback *fb;

    if (!s) return NULL;

    feedback = ((IMFeedbackList *)
                s->If->m->iml_new(s, sizeof(IMFeedbackList) * size));
    for (i = 0; i < size; i++) {
        fbl = &feedback[i];
        fbl->count_feedbacks = 1;
        fb = ((IMFeedback *) s->If->m->iml_new(s, sizeof(IMFeedback) * 4));
        fbl->feedbacks = fb;
        memset(fbl->feedbacks, 0, sizeof(IMFeedback) * 4);
    }
    return feedback;
}

IMText*
create_IMText(iml_session_t *s, int len)
{
    IMText *p;

    if (!s) return NULL;

    p = (IMText *) s->If->m->iml_new(s, sizeof(IMText));
    memset(p, 0, sizeof(IMText));
    p->encoding = UTF16_CODESET;
    p->text.utf_chars = ((UTFCHAR *)
                         s->If->m->iml_new(s, sizeof(UTFCHAR) * (len + 1)));
    p->char_length = len;
    p->feedback = create_feedback(s, len);

    return p;
}

int
ustrlen(UTFCHAR* ustr) {
  int i;

  if( ustr == NULL ) return 0;
  if( ustr[0] == 0x0000 ) return 0;

  for(i=0; ; i++) {
    if (ustr[i] == 0x0000)
      return i;
  }

}

UTFCHAR*
UTF8_to_UTFCHAR(unsigned char* str) {
  UTFCHAR *p, *ustr = NULL;
  int len, ulen;

  if( str == NULL ) return NULL;
  if( *str == '\0' ) return NULL;

  if( csconv_utf8_cd == NULL ) {
    csconv_utf8_cd = csc_open("UTF-16", "UTF-8");
    if( csconv_utf8_cd == NULL ) {
      wnn_printf(("csconv_open failed.\n"));
      return NULL;
    }
  }

  len = strlen(str);

  ulen = sizeof(UTFCHAR)*(len+1);
  p = ustr = (UTFCHAR*)calloc(len+1, sizeof(UTFCHAR));

  csc_conv(csconv_utf8_cd, (const char**)&str, &len, (char**)&ustr, &ulen);

  *ustr = 0;

  return p;
}

UTFCHAR*
euc2UTFCHAR(unsigned char* str) {
  UTFCHAR *p, *ustr = NULL;
  int len, ulen;

  if( str == NULL ) return NULL;
  if( *str == '\0' ) return NULL;

  if( csconv_cd == NULL ) {
    csconv_cd = csc_open_locale("ja_JP.eucJP", "UTF-16", "MultiByte");
    if( csconv_cd == NULL ) {
      wnn_printf(("csconv_open failed.\n"));
      return NULL;
    }
  }

  len = strlen(str);

  ulen = sizeof(UTFCHAR)*(len+1);
  p = ustr = (UTFCHAR*)calloc(len+1, sizeof(UTFCHAR));

  csc_conv(csconv_cd, (const char**)&str, &len, (char**)&ustr, &ulen);

  *ustr = 0;

  return p;
}

IMText*
freewnn_UTF8_to_IMText(iml_session_t *s, char* str) {
  IMText* p = NULL;
  UTFCHAR *ustr = NULL;

  ustr = UTF8_to_UTFCHAR(str);

  p = create_IMText(s, ustrlen(ustr));
  memcpy(p->text.utf_chars, ustr, (ustrlen(ustr)+1)*sizeof(UTFCHAR));

  return p;
}

IMText*
freewnn_string2IMText(iml_session_t *s, char* str) {
  IMText* p = NULL;
  UTFCHAR *ustr = NULL;

  ustr = euc2UTFCHAR(str);

  p = create_IMText(s, ustrlen(ustr));
  memcpy(p->text.utf_chars, ustr, (ustrlen(ustr)+1)*sizeof(UTFCHAR));

  return p;
}

void
commit_string(iml_session_t *s) {
  iml_inst *lp = NULL;
  iml_inst *rrv = NULL;
  IMText* p = NULL;
  FreeWnnSession* session_data = freewnn_session_data(s);
  char buf[BUFSIZE*2];

  bzero(buf, BUFSIZE*2);
  if( strlen(session_data->preedit_buf) > 0 )
    strcpy(buf, session_data->preedit_buf);

  session_data->kanji_on = False;

  if( strlen(buf) == 0 )
    return;

  bzero(session_data->preedit_buf, sizeof(char)*BUFSIZE);

  p = freewnn_string2IMText(s, buf);
  lp = s->If->m->iml_make_commit_inst(s, p);
  s->If->m->iml_link_inst_tail(&rrv, lp);
  s->If->m->iml_execute(s, &rrv);
}

void
preedit_done(iml_session_t *s) {
  FreeWnnSession* session_data = freewnn_session_data(s);

  if( session_data->preedit_start == True ) {
    iml_inst *lp;
    lp = s->If->m->iml_make_preedit_done_inst(s);
    s->If->m->iml_execute(s, &lp);
    session_data->preedit_start = False;
  }
}

void
preedit_draw(iml_session_t *s) {
  iml_inst *lp = NULL;
  iml_inst *rrv = NULL;
  UTFCHAR *ustr = NULL;
  int i;
  IMText *p = NULL;
  FreeWnnSession* session_data = freewnn_session_data(s);
  IMFeedbackList *fbl;
  IMFeedback *fb;

  if( session_data->preedit_start == False) {
    lp = s->If->m->iml_make_preedit_start_inst(s);
    s->If->m->iml_link_inst_tail(&rrv, lp);
    session_data->preedit_start = True;
  }

  ustr = euc2UTFCHAR(session_data->preedit_buf);

  if( ustrlen(ustr) == 0 ) {
    free(ustr);
    return;
  }

  p = create_IMText(s, ustrlen(ustr));
  memcpy(p->text.utf_chars, ustr, (ustrlen(ustr)+1)*sizeof(UTFCHAR));
  for(i=0;i<ustrlen(ustr);i++) {
    fbl = &p->feedback[i];
    fb = &fbl->feedbacks[0];
    IM_FEEDBACK_TYPE(fb) = IM_DECORATION_FEEDBACK;
    IM_FEEDBACK_VALUE(fb) = IMUnderline;
    IM_FEEDBACK_COUNT(fbl) = 1;
  }

  lp = s->If->m->iml_make_preedit_draw_inst(s, p);
  s->If->m->iml_link_inst_tail(&rrv, lp);
  s->If->m->iml_execute(s, &rrv);
}

static void
dlopen_csconv()
{
      csc_handle = dlopen(CSC_PATH, RTLD_LAZY);
      if (NULL == csc_handle) {
        csc_handle = (void *)(-1);
        return;
      }

      csc_open_locale = (csc_open_locale_t)dlsym(csc_handle, CSC_OPEN_LOCALE);
      csc_open = (csc_open_t)dlsym(csc_handle, CSC_OPEN);
      csc_conv = (csc_conv_t)dlsym(csc_handle, CSC_CONV);
      csc_close = (csc_close_t)dlsym(csc_handle, CSC_CLOSE);

      if ((NULL == csc_open) ||
          (NULL == csc_conv) || (NULL == csc_close)) {
        dlclose(csc_handle);
        csc_handle = (void *)(-1);
        return;
      }
}

void
freewnn_process_keyevent(iml_session_t *s, IMKeyListEvent* kev) {
  FreeWnnSession* session_data = freewnn_session_data(s);

  IMKeyEventStruct *k = (IMKeyEventStruct*)kev->keylist;

  if( k->keyCode == IM_VK_SPACE && (k->modifier & IM_CTRL_MASK) ) {
    if( session_data->conv_on == True ) {
      freewnn_conversion_off(s);
    } else {
      freewnn_conversion_on(s);
    }
    return;
  }

  if( session_data->conv_on == True ) {
    if( k->keyCode == IM_VK_ENTER ) {
      commit_string(s);
      preedit_done(s);
      return;
    }
    if( k->keyCode == IM_VK_SPACE ) {
      freewnn_conversion(s);
      preedit_draw(s);
      return;
    }
    if( k->keyCode >= 65 && k->keyCode <= 90 ) {
      buffer_append(session_data->preedit_buf, k->keyCode - 65 + 'a');
      preedit_draw(s);
    }
  } else {
    iml_inst* lp;
    lp = s->If->m->iml_make_keypress_inst(s, ((IMKeyEventStruct*)kev->keylist));
    s->If->m->iml_execute(s, &lp);
  }
}

void
if_GetIfInfo(IMArgList args, int num_args) {
  int i;
  wnn_printf(("if_GetIfInfo()\n"));
  
  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) & if_methods;
      break;
    case IF_LE_NAME:
      args->value = (IMArgVal) & lename;
      break;
    case IF_SUPPORTED_LOCALES:
      args->value = (IMArgVal) & locales;
      break;
    case IF_SUPPORTED_OBJECTS:
      break;
    case IF_NEED_THREAD_LOCK:
      args->value = (IMArgVal) False;
      break;
    default:
      break;
    }
  }
}

Bool
if_freewnn_OpenIF(iml_if_t * If) {

  if( csc_handle == NULL )
    dlopen_csconv();

    wnn_printf(("if_freewnn_OpenIF()\n"));
    return True;
}

Bool
if_freewnn_CloseIF(iml_if_t * If)
{
    wnn_printf(("if_freewnn_CloseIF()\n"));
    return True;
}



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

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

Bool
if_freewnn_OpenDesktop(iml_desktop_t * desktop, IMArgList args, int num_args) {
    wnn_printf(("if_freewnn_OpenDesktop()\n"));
    
    return True;
}

Bool
if_freewnn_CloseDesktop(iml_desktop_t * desktop) {
    wnn_printf(("if_freewnn_CloseDesktop()\n"));
    return True;
}

Bool
if_freewnn_CreateSC(iml_session_t *s, IMArgList args, int num_args) {

  struct passwd *p = NULL;
  struct wnn_env* wenv = NULL;
  char* envname = "openi18n";
  FreeWnnSession* session_data
    = (FreeWnnSession*)calloc(sizeof(FreeWnnSession), 1);

  session_data->kanji_on = False;
  session_data->conv_on = False;
  session_data->preedit_start = False;
  session_data->preedit_buf = (char*)calloc(sizeof(char), BUFSIZE);
  p = getpwuid(getuid());
  if( p )
    envname = p->pw_name;
  session_data->wbuf = jl_open_lang(envname, getenv("JSERVER"), "ja_JP", NULL,
    printError, printConfirm, 0);

  if( session_data->wbuf == NULL ) {
    wnn_printf(("jl_open_lang() failed.\n"));
    return False;
  }

  wenv = jl_env_get(session_data->wbuf);
  if( wenv == NULL ) {
    wnn_printf(("jl_env_get() failed.\n"));
    return False;
  }

  jl_set_env_wnnrc(wenv, WNNRCFILE, printConfirm, printError);

  s->specific_data = (void*)session_data;
    
  return True;
}

Bool
if_freewnn_DestroySC(iml_session_t * s) {
    wnn_printf(("if_freewnn_DestroySC()\n"));
    
    return True;
}

Bool
if_freewnn_GetSCValues(iml_session_t * s, IMArgList args, int num_args) {
    wnn_printf(("if_freewnn_GetSCValues()\n"));

    return True;
}

Bool
if_freewnn_SetSCValues( iml_session_t * s, IMArgList args, int num_args) {
    int i;
    IMArg *p = args;
    
    wnn_printf(("if_freewnn_SetSCValues()\n"));
    
    for (i = 0; i < num_args; i++, p++) {
        switch (p->id) {
            case SC_TRIGGER_ON_NOTIFY:
                wnn_printf(("	SC_TRIGGER_ON_NOTIFY: received\n"));
                freewnn_conversion_on(s);
                freewnn_status_draw(s, "  [あ]\n FreeWnn ");
                break;
            case SC_TRIGGER_OFF_NOTIFY:
                wnn_printf(("	SC_TRIGGER_OFF_NOTIFY: received\n"));
                freewnn_conversion_off(s);
                freewnn_status_draw(s, "   [A]\n FreeWnn ");
                break;
            case SC_REALIZE:
                break;
            default:
                break;
            }
    }
    return True;
}

IMText *
if_freewnn_ResetSC(iml_session_t * s) {
    wnn_printf(("if_freewnn_ResetSC()\n"));
    
    return (IMText *) NULL;
}

void
if_freewnn_SetSCFocus(iml_session_t * s) {
    wnn_printf(("if_freewnn_SetSCFocus()\n"));
}

void
if_freewnn_UnsetSCFocus(iml_session_t * s) {
    wnn_printf(("if_freewnn_UnsetSCFocus()\n"));
}

void
if_freewnn_SendEvent(iml_session_t * s, IMInputEvent * ev) {
  wnn_printf(("if_freewnn_SendEvent()\n"));
    
  if (ev->type == IM_EventKeyList) {
    freewnn_process_keyevent(s, (IMKeyListEvent*)ev);
  }
}

void
freewnn_status_draw(iml_session_t *s, char* str)
{
  IMText *p = NULL;
  iml_inst *lp = NULL;
  iml_inst *rrv = NULL;
  p = freewnn_UTF8_to_IMText(s, str);
  lp = s->If->m->iml_make_status_draw_inst(s, p);
  s->If->m->iml_link_inst_tail(&rrv, lp);
  s->If->m->iml_execute(s, &rrv);
}
