/**********************************************************************
 
	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_AddrdbImport();

void
init_AddrdbImport(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"AddrdbImport"),
		get_func_prim(xl_AddrdbImport, FO_NORMAL, 0, 3, 3));
}

XL_SEXP *
xl_AddrdbImport(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
XL_SEXP * dirname;
/*
XL_SEXP * db_sym;
XL_SEXP * db_sexp;
ADDRDB* db_ptr;
*/
ADDRDB* db;
int ret;
ADDRDB_OPTION option;

	option = 0;
	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 ){
				goto unsupport_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;
				}
				else if(l_strcmp(sf->data,l_string(std_cm,"skip")) == 0){
					option = ADOPT_INSERT_SKIP_ON_KEY_COLLISION;
				}
			}
		}
	}

	dirname = get_el(s,2);
	if ( get_type(dirname) != XLT_STRING )
		goto type_missmatch;
	
	db = addrdb_get_db_from_symbol(env, get_el(s,1));
	if(db == NULL)
		goto type_missmatch;
	
	if(option!=0){
		addrdb_set_option(db, option);
	}
	ret = addrdb_kokudo_import_csv_batch(db, n_string(std_cm,((XL_STRING*)dirname)->data));
	
	if ( ret == -1 )
		goto cannot_open;
	
	return get_integer(ret,0);

type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"AddrdbImport"),
		n_get_string("type missmatch"));
cannot_open:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_OPEN_FILE,
		l_string(std_cm,"AddrdbImport"),
		n_get_string("cannot open the file"));
unsupport_locale:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_OPEN_FILE,
		l_string(std_cm,"AddrdbImport"),
		n_get_string("locale attribute error"));

}

