/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.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	"xlerror.h"
#include	"gbview.h"
#include	"xl.h"

#include "HTMLDB.h"

XL_SEXP * xl_Option();

void
init_Option(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Option"),
		get_func_prim(xl_Option,FO_APPLICATIVE,0,1,1));
}


XL_SEXP *
exec_option(L_CHAR * opt,XL_SEXP * d,L_CHAR * url,XL_FILE * f,int line)
{
char u[2048];
L_CHAR * dir;
XL_SEXP * dd;

	if ( d == 0 && url == 0 || opt == 0 )
		return 0;
	if ( l_strcmp(opt,l_string(std_cm,"force")) == 0 ) {
		if ( d && d->integer.data < 0 )
			goto invalid_page;
	}
	else if ( l_strcmp(opt,l_string(std_cm,"immidiate")) == 0 ) {
		if ( current_page == 0 )
			return 0;
		dd = GetElement(l_string(std_cm,current_page),HTMLDataBase);
		if ( dd == 0 )
			return 0;
		if ( d ) {
			if ( dd != d )
			return 0;
		}
		else {
			d = GetElement(url,HTMLDataBase);
			if ( d == 0 )
				return 0;
			if ( current_page ==0 ||
				l_strcmp(l_string(std_cm,current_page),
					url) )
				return 0;
			d = 0;
		}
	}
	else if ( l_strcmp(opt,l_string(std_cm,"regist")) == 0 ) {
		return 0;
	}
	else {
		return get_error(
			f,
			line,
			XLE_PROTO_INV_PARAM,
			l_string(std_cm,"HTMLdb option"),
			n_get_string("invalid option"));
	}

	if ( d ) {
		dir = GetURLString(d);
		sprintf(u,"http://%s:%i%s",
			http_hostname,
			http_port,
			n_string(std_cm,dir));
		set_change_page(u,0);
	}	
	else {
		sprintf(u,"http://%s:%i%s",
			http_hostname,
			http_port,
			n_string(std_cm,url));
		set_change_page(u,0);
	}
	return 0;
invalid_page:
	return get_error(
		f,
		line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"HTMLdb option"),
		n_get_string("invalid option"));
}

XL_SEXP *
xl_Option(XLISP_ENV * env,XL_SEXP * s,
	  XLISP_ENV * arg_env,XL_SYM_FIELD * sf)
{
XL_SEXP * ret;
	ret = exec_option(GetOption(l_string(std_cm,"update"),sf),
		0,
		GetOption(l_string(std_cm,"url"),sf),
		s->h.file,
		s->h.line);
	
	return ret;
}
