/**********************************************************************
 
	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	<math.h>
#include	"xlerror.h"
#include	"xl.h"
#include	"pmd.h"
#include	"pfc.h"
#include	"pri_level.h"


XL_SEXP * xl_trigger();
PFC pmd_pfc;
extern int trigger_active;


int trigger_count;

void
init_trigger(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"trigger"),
		get_func_prim(xl_trigger,FO_APPLICATIVE,0,4,4));
}



XL_SEXP *
xl_trigger(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * db;
XL_SEXP * target;
XL_SEXP * req_interval;
int _req_interval;
int interval;
XL_SEXP * ret;

	if ( trigger_active == 0 ) {
		ret = get_error(
			s->h.file,
			s->h.line,
			XLE_PROTO_UNSUPPORT_MODE,
			l_string(std_cm,"trigger"),
			n_get_string("trigger is inactive"));
		return ret;
	}
	db = get_el(s,1);
	target = get_el(s,2);
	req_interval = get_el(s,3);
	if ( get_type(db) != XLT_STRING )
		goto type_missmatch;
	if ( get_type(target) != XLT_STRING )
		goto type_missmatch;
	if ( get_type(req_interval) != XLT_INTEGER )
		goto type_missmatch;
	_req_interval = req_interval->integer.data;

	init_pfc();

	interval = get_pfc_interval(&pmd_pfc);

	if ( interval > _req_interval )
		_req_interval = interval;
	insert_pmd_que(db->string.data,target->string.data,
		_req_interval);


	ret = get_integer(interval,l_string(std_cm,"sec"));
	trigger_count ++;
	return ret;

type_missmatch:


	ret = get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"trigger"),
		n_get_string("type missmatch"));

	return ret;
}


