#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <dlfcn.h>
#include <libgen.h>
#include <unistd.h>
#include "ImmDefs.h"
#include "ImmModule.h"

long int get_imm_type (const char *tab_name)
{
	// tab_name may be in relative path / absolute path, or other.
	char *pname, *bname;

	pname = strdup (tab_name);
	bname = basename (pname);
	
	if (strcmp (bname, "cj.tab") == 0)
		return IMM_LC_BIG5;
}

void print_func_list (void)
{
	printf ("1.  Open Module\n");
	printf ("2.  Configure Input Area\n");
	printf ("3.  Key Filter\n");
	printf ("4.  Get Input Display\n");
	printf ("5.  Get Select Display\n");
	printf ("6.  Get Item\n");
	printf ("7.  Save Module\n");
	printf ("8.  Close Module\n");
	printf ("9.  Reset Input\n");
	printf ("10. Add Phrase\n");
	printf ("11. Modify Phrase Item\n");
	printf ("12. Flush\n");
}

void get_tab_name (char *tab_name)
{
	printf ("Enter Input Method Name: ");
	scanf  ("%s", tab_name);
	printf ("\n");
}

unsigned char get_input_key (void)
{
	unsigned char line[10] = "";

	fflush (stdin);
	printf ("Input Key >> ");
	while (! (isalpha (line[0]) || line[0] == 32))
	{
		fgets (line, 10, stdin);
	}
	fflush (stdin);

	return line[0];
}

int main (void)
{
	IMM_CLIENT 				*cli_handle;
	void 					*lib_handle;
	struct ImmOperation 	*op_list;
	char  					tab_name[20] = "";
	unsigned char			op_input;

	unsigned char input_code = 0;
	unsigned char buffer[64] = "";
	char ch_len = 0;


	printf ("++===========================================++\n");
	printf ("             TL_hzinput.so tester              \n");
	printf ("++===========================================++\n");

	lib_handle = dlopen ("./TL_hzinput.so", RTLD_LAZY);
	if (lib_handle == NULL)
	{
		printf ("Error: Cannot open TL_hzinput.so\n");
		exit (1);
	}

	op_list = (struct ImmOperation *) dlsym (lib_handle, "ImmOp_Ptr");
	if (op_list == NULL)
	{
		printf ("Error: Fail to open ImmOp_Ptr\n");
		exit (1);
	}
	
	while (1)
	{
		putchar ('\n');
		printf ("Please select an operation:\n");
		print_func_list ();
		printf ("->> ");
		scanf ("%d", &op_input);

		switch (op_input)
		{
			case 1:
				get_tab_name (tab_name);
				cli_handle = op_list->open (tab_name, get_imm_type (tab_name));

				if (cli_handle == NULL)
				{
					printf ("Error: Fail to open %s\n", tab_name);
					exit (1);
				}
				op_list->ResetInput (cli_handle);
				op_list->ConfigInputArea (cli_handle, 10);
				break;

			case 3:
				input_code = get_input_key ();
				op_list->KeyFilter (cli_handle, input_code, buffer, (int*)&ch_len);
				if (ch_len)
					printf ("KeyFilter () result : %s\n", ch_len);
				break;

			case 8:
				if (!op_list->close (cli_handle))
					printf ("Failed\n");
				else
					printf ("Success\n");
				break;

			default:
				printf ("Not Implement, try others\n");
				break;
		}
		usleep (2000);
	}
}
