#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <strings.h>
#include "SunIM.h"
#include "kole.h"
#include "koinput.h"
#include "encode.h"
#include "iml.h"
#include "logf.h"

int encode_to_unicode(int encode, unsigned char *from, int from_len,
				  UTFCHAR *to, int to_len)
{
	int to_left, ret;
	char *to_ptr;

	logf("encode_to_unicode: from:%s, encode:%d\n", from, encode);
	to_left = to_len;
	ret = Convert_Native_To_UTF16(encode, (char *)from, from_len, (char **)&to, (size_t *)&to_left);
	logf("encode_to_unicode: return:%d, to_left:%d\n", ret, to_left);
	if (ret == -1) {
		to[0] = (UTFCHAR)0;
	} else {
		if (to_left > 2) {
			to_ptr = (char *)to;
			to_ptr[to_len - to_left] = 0;
			to_ptr[to_len - to_left +1] = 0;
		}
	}
	return(ret);
}

void encode_draw_preedit(iml_session_t *s, int encode, unsigned char *preedit_buf, int caret)
{
	static UTFCHAR Preedit_Buffer[MAX_PREEDIT_CHAR_NUM * 2];
	int preedit_len, caret_pos;
	
	preedit_len = strlen((char *)preedit_buf);
	if (preedit_len <=0)
		iml_preedit_enddraw(s);
	/*
	 The value of encode is from IMEBuffer->encode member, which is
	 default encoding the language engine is using internally
	*/
	encode_to_unicode(encode, preedit_buf, preedit_len, Preedit_Buffer, MAX_PREEDIT_CHAR_NUM * 2);
	iml_preedit_draw(s, Preedit_Buffer, caret);
}

void encode_draw_status(iml_session_t *s, int encode, unsigned char *status_buf)
{
	static UTFCHAR Status_Buffer[MAX_STATUS_CHAR_NUM * 2];
	int status_len;
	int i, len;

	status_len = strlen((char *)status_buf);
	if (status_len <= 0)
		return;

	encode_to_unicode(encode, status_buf, status_len, Status_Buffer, MAX_STATUS_CHAR_NUM * 2);
	iml_status_draw(s, Status_Buffer);
}

void encode_draw_candidates(iml_session_t *s, int encode, unsigned char **lookup_buf, int lookup_num, int lookup_label_type)
{
	static UTFCHAR *Lookup_Buffer[MAX_CANDIDATES_NUM];
	static UTFCHAR Lookup_Items_Buffer[MAX_CANDIDATES_NUM][MAX_CANDIDATE_CHAR_NUM * 2];
	static int bLookupInited = 0;

	int i, lookup_len;

	if (bLookupInited == 0) {
		bLookupInited = 1;
		for (i=0; i<MAX_CANDIDATES_NUM; i++)
			Lookup_Buffer[i] = Lookup_Items_Buffer[i];
	}

	if (lookup_num <= 0)
		iml_lookup_enddraw(s);

	/* Notes that Lookup_Buffer has point to Lookup_Items_Buffer */
	for (i=0; i<lookup_num; i++) {
		lookup_len = strlen((char *)lookup_buf[i]);
		encode_to_unicode(encode, lookup_buf[i], lookup_len, Lookup_Items_Buffer[i], MAX_CANDIDATE_CHAR_NUM * 2);
	}

	iml_lookup_draw(s, Lookup_Buffer, lookup_num, lookup_label_type);
}

void encode_commit(iml_session_t *s, int encode, unsigned char *commit_buf)
{
	static UTFCHAR Commit_Buffer[MAX_COMMIT_CHAR_NUM * 2];
	int commit_len;

	commit_len = strlen((char *)commit_buf);
	if (commit_len <= 0)
		return;

	encode_to_unicode(encode, commit_buf, commit_len, Commit_Buffer, MAX_COMMIT_CHAR_NUM * 2);
	iml_commit(s, Commit_Buffer);
}

