#include <stdio.h>
#include <assert.h>
#include <iconv.h>
#include <glib.h>

#include "utfchar.h"
#include "hhentry.h"
#include "tree.h"

#ifdef TEST_RUN


void
node_print (void *data)
{
  HHItem *p = (HHItem *) data;
  hhitem_print_string (p, NULL);
  printf ("\n");
  return;
  
}

void
my_print (void *data)
{
  TreeNode *node = (TreeNode *)data;
  
  HHItem *p;
  int len;
  char from_buffer[100], to_buffer[100];
  int  from_i = 0, to_i = 0;
  char *f_ptr, *t_ptr;
  iconv_t cd;
  size_t ret;

  
  p = node->data;
  len = strlen (p->hangul);
  
  memset (from_buffer, 0, 100); memset (to_buffer, 0, 100);
  memcpy (from_buffer, p->hangul, sizeof (UTFCHAR) * (len + 1));
  
  f_ptr = from_buffer, t_ptr = to_buffer;
  from_i = len * sizeof (UTFCHAR) , to_i = 100;
  
  cd = iconv_open ("EUC-KR", "UTF16");
  if (cd == (iconv_t) -1) {
    fprintf (stderr, "iconv_open error, returning..\n");
    return;
  }
  ret = iconv (cd, &f_ptr, &from_i, &t_ptr, &to_i);
  if (ret == (size_t) -1){
    fprintf (stderr, "iconv error, returning...\n");
    return;
  }
  fprintf (stdout, "%s\n", to_buffer);
  iconv_close (cd);
  return;
}

unsigned char *
convert_u16_to_u8 (UTFCHAR *u16str)
{
  gchar *u8str;
  int u16len = _utfchar_length (u16str) * sizeof (UTFCHAR);
  int bytes_read = 0;
  int bytes_written = 0;
  GError *gerror = NULL;
  
  u8str = g_convert ((const gchar *)u16str,
		     u16len,
		     "UTF-8", "UTF-16",
		     &bytes_read,
		     &bytes_written,
		     &gerror);
  if (gerror)
    return NULL;

  return u8str;
}

int
main (int argc, char **argv)
{

  HHList *hash_table;
  int table_size;

  int n_trees;
  Tree *p_trees;
  TreeNode *p_treenode;
  TreeNode *search_result;
  UTFCHAR u16_word[10];
  int n_hanja = 0;
  unsigned char *u8_hangul;

  int i,j;
  int hashval;


  fprintf (stdout, "reading dictionary into hash table...\n");
  construct_binary_tree_from_file (argv[1], &p_trees, &n_trees );
  fprintf (stdout, "finished reading dictionary\n");

  tree_print (p_trees, (void * (*) (void *)) node_print);
  
  /*
  for (i = 0; i < n_trees; i++){
    printf ("Tree id:%d\n", i);

    printf ("===========================================\n");
  }
  */

  memset (u16_word, 0, sizeof (u16_word));
    /*
  while (scanf ("%x%x",&u16_word[0], &u16_word[1])){
    */
  while (scanf ("%x",&u16_word[0])){

    hashval = hash (u16_word);
    printf ("hasval : %d\n", hashval);
    u8_hangul = convert_u16_to_u8 (u16_word);
    search_result = tree_search_hangul (p_trees + hashval, u8_hangul);

    if (search_result){
      printf ("found  from tree...\n");
      n_hanja = search_result->data->n_hanja;
      printf ("%s\n", search_result->data->hangul);
      for (i = 0 ; i < n_hanja; i++)
	printf ("%s ", search_result->data->hanja_list[i]);
      printf ("\n");
    } else
        printf ("not found.....\n");
    /*
    tree_print (p_trees + hashval, (void * (*) (void *)) node_print);
    */
    memset (u16_word, 0, sizeof (u16_word));
  }
  return 0;
}

#endif
