/**********************************************************************
 
	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	"resource.h"
#include	"xl.h"
#include	"memory_debug.h"
#include	"rs_cache.h"
#include	"rcache.h"

XL_SEXP * 
load_meta(int ses,char * mode,L_CHAR * target)
{
XL_SEXP * ret;
XL_SEXP * gt;
L_CHAR * f;
URL uu;
void gc_gb_sexp();
RS_BUF b;
int flags;

	gc_push(0,0,"remote_fetch");

	if ( strcmp(mode,"data") == 0 ||
			strcmp(mode,"meta") == 0 ) {
		ret = get_meta_cache_str(target,mode);
		if ( ret ) {
			gc_pop(ret,gc_gb_sexp);
			return ret;
		}
		memset(&b,0,sizeof(b));
		if ( strcmp(mode,"data") == 0 )
			flags = RSQ_DATA;
		else if ( strcmp(mode,"meta") == 0 )
			flags = RSQ_META;
		else	flags = RSQ_LUMP;
		if ( get_rs_resource_cache(&b,target,flags) == 0 ) {

			if ( b.meta )
				ret = b.meta;
			else if ( b.data )
				ret = b.data;
			else	ret = b.lump;

			if ( get_type(ret) != XLT_ERROR && ret ) {


				get_url2(&uu,target);
				new_meta_cache(&uu,ret,mode[0]);
				free_url(&uu);

				gc_pop(ret,gc_gb_sexp);
				return ret;
			}
		}
	}

	get_url2(&uu,target);

	gt = get_symbol(l_string(std_cm,"Get"));
	set_attribute(gt,
		l_string(std_cm,"mode"),
		l_string(std_cm,mode));

	f = get_url_filepath(&uu);

	ret = remote_session(
		gblisp_top_env0,
		ses,
		&uu,
		0,
		l_string(std_cm,"user"),
		l_string(std_cm,"Get"),
		List(List(gt,
			get_string(f),
			-1),
			-1),
		0,0,0,0);
	d_f_ree(f);

if ( get_type(ret) == XLT_ERROR ){
log_printf(LOG_ERROR,LOG_LAYER_GB,0,"loadmeta(%i)(%s) %ls = ",get_tid(),mode,get_url_str2(&uu));
log_print_sexp(LOG_ERROR,LOG_LAYER_GB,0,"loadmeta",ret,0);
}

	if ( get_type(ret) != XLT_ERROR &&
			(strcmp(mode,"meta") == 0 || strcmp(mode,"data") == 0) ) {



		memset(&b,0,sizeof(b));
		if ( strcmp(mode,"meta") == 0 )
			b.meta = ret;
		else if ( strcmp(mode,"data") == 0 )
			b.data = ret;
		else	b.lump = ret;
		b.url = target;
		set_rs_resource_cache(&b);

		new_meta_cache(&uu,ret,mode[0]);
	}

	free_url(&uu);

	gc_pop(ret,gc_gb_sexp);
	return ret;
}



