/**********************************************************************
 
	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	<stdlib.h>
#include	"http.h"
#include	"gbview.h"
#include	"task.h"
#include	"xl.h"
#include	"pri_level.h"

int http_port;
char http_hostname[100];

void http_task();
void polling_tick();

void
init_http_server()
{
STREAM * sd;
int i;
char * buf;

int port;

	init_http(); 

	port = 9091 + (get_xltime() % (10000-9091-100));
	sd = init_server(&http_port,port,100);
	if ( sd == 0 ) {
		fprintf(stderr,"cannot open the HTTP SERVER\n");
		exit(1);
	}

	create_task(http_task,(int)sd,PRI_HTMLDB);
	printf("HTTP PORT ====> %i\n",http_port);
	strcpy(http_hostname,"127.0.0.1");
	new_tick(polling_tick,POLLING_TICK_INTERVAL,0);
}


void
http_task(TKEY key)
{
STREAM * sd;
HTTP_ENV he;
char my_host[100];
XL_INTERPRETER * xli;
	sd = (STREAM*)GET_TKEY(key);

	xli = new_xl_interpreter();
	xli->a_type = XLA_SELF;
	setup_i(xli);

	he.polcnt = 0;
	for ( ; ; ) {
		he.key = accept_connection(sd);
		he.port = http_port;
		he.host = http_hostname;
		he.hostpath = 0;
		http_get(&he);
		close_key(he.key);
	}
}
