/**********************************************************************
 
	Copyright (C) 2004 Tomohito Nakajima <nakajima@zeta.co.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/


#include	<fcntl.h>
#include	"xlerror.h"
#include	"xl.h"
#include	"addrdb_jp.h"
#include	"xl_addrdb.h"

XL_SEXP * xl_AddrdbOpen();

ADDRDB *addrdb_get_db_from_symbol(XLISP_ENV *env, XL_SEXP *sym)
{
XL_SEXP*s;

	if ( get_type(sym) != XLT_SYMBOL )
		return 0;
	
	s = eval(env, sym);
	if( get_type(s) != XLT_PTR )
		return 0;
	
	return ((XL_PTR*)s)->ptr;
}

void
init_AddrdbOpen(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"AddrdbOpen"),
		get_func_prim(xl_AddrdbOpen, FO_NORMAL, 0, 2, 2));
}

XL_SEXP *
xl_AddrdbOpen(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
XL_SEXP * filename;
L_CHAR * encoding;
ADDRDB_LOCALE *locale;
ADDRDB *db;
ADDRDB_OPTION option;

encoding = l_string(std_cm,"UTF-8");

	locale = addrdb_kokudo_get_locale();
	option = ADOPT_INSERT_SKIP_ON_KEY_COLLISION;

	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"locale")) == 0 ) {
			if ( l_strcmp(sf->data,l_string(std_cm,"kokudo")) == 0 ){
				locale = addrdb_kokudo_get_locale();
			}
		}
		else if ( l_strcmp(sf->name,l_string(std_cm,"option")) == 0 ) {
			if ( l_strcmp(sf->data,l_string(std_cm,"overwrite")) == 0 ){
				option = ADOPT_INSERT_OVERWRITE_ON_KEY_COLLISION;
			}
		}
	}
	filename = get_el(s,1);
	if ( get_type(filename) != XLT_STRING )
		goto type_missmatch;

	db = addrdb_open(n_string(std_cm, filename->string.data), locale, option);
	
	if ( db == 0 )
		goto cannot_open;
	
	return get_ptr(db,0);

type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"AddrdbOpen"),
		n_get_string("type missmatch"));
cannot_open:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_OPEN_FILE,
		l_string(std_cm,"AddrdbOpen"),
		n_get_string("cannot open the file"));
}

