/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <X11/Xlib.h>
#include <Metview.h>
#include <Cached.h>

//-- env.variables MV_BROWSER_* defined in: ./scripts/metview_local.*
Cached myBrowser  = "firefox";    //-- can be set with MV_BROWSER_NAME
char expMozVers[] = "5.1\0     "; //-- can be set with MV_BROWSER_VERS

const char* expected_mozilla_version = (const char*)expMozVers;


extern "C" int mozilla_remote_commands (Display *dpy, Window window, char **commands);
extern "C" int mozilla_remote_check_window (Display *dpy, Window window);

class WebAccess : public MvService {
protected:
	Display *dpy_;
	WebAccess(char* a);
	void send(MvRequest&,Window);
};

class NormalAccess : public WebAccess {
	void serve(MvRequest&,MvRequest&);
public:
	NormalAccess() : WebAccess("WEBACCESS")			{};
};

class DropAccess : public WebAccess {
	Cached applications_;
	Cached catalogue_;
	void serve(MvRequest&,MvRequest&);
public:
	DropAccess();
};

static int xerror(Display*,XErrorEvent*)
{
	return 0;
}

WebAccess::WebAccess(char *name):
	MvService(name)
{
	saveToPool(0);
	dpy_ = XOpenDisplay(0);
	XSetErrorHandler(xerror);
	if( getenv("MV_BROWSER_NAME") )
	{
		myBrowser = getenv("MV_BROWSER_NAME");
		cout << "Help browser set to " << (const char*)myBrowser << endl;
	}
	if( getenv("MV_BROWSER_VERS") )
	{
		strcpy( expMozVers, getenv("MV_BROWSER_VERS"));
		cout << "Help browser version set to " << expected_mozilla_version << endl;
	}
}


void WebAccess::send(MvRequest& in,Window w)
{
	char buf1[10240];
	char buf2[10240];
	int n = 0;
	char* cmd[10];

	in.print();

	const char* url     = in("URL");
	const char* save    = in("SAVE");
	const char* type    = in("TYPE");

	if(url)
	{
		sprintf(buf1,"openURL(%s)",url);
		cmd[n++] = buf1;
	}

	if(save)
	{
		if(!type) type = "HTML";
		sprintf(buf2,"saveAs(%s,%s)",save,type);
		cmd[n++] = buf2;
	}

	cmd[n] = 0;


	if(mozilla_remote_commands (dpy_,w,cmd) != 0)
	{
		// Start netscape first
		Cached myStartCmd = myBrowser + "&";
		system( (const char*)myStartCmd );

		for(int i = 0; i < 5; i++)
		{
			sleep(2);
			if(mozilla_remote_commands (dpy_,0,cmd) == 0)
				return;
		}
		setError(1,"Could not connect to a Netscape window");
	}


}

void NormalAccess::serve(MvRequest& in,MvRequest& out)
{
	send(in,0);
}

DropAccess::DropAccess() : WebAccess("DROP")
{
	request* r  = mars.setup;
	Cached web       = "web";
	Cached catalogue = "catalogue";
	Cached applications = "applications";

	while(r)
	{
		if(r->name == web)
		{
			const char* p = get_value(r,"page",0);
			if(p == catalogue)    catalogue_ = get_value(r,"url",0);
			if(p == applications) applications_ = get_value(r,"url",0);
		}
		r = r->next;
	}
}

const Cached RETRIEVE  = "RETRIEVE";
const Cached WEBACCESS = "WEBACCESS";

void DropAccess::serve(MvRequest& in,MvRequest& out)
{
	Window w = long(in("WINDOW"));

	while(w &&  !mozilla_remote_check_window(dpy_,w))
	{
		Window  root;
		Window* children;
		unsigned int num = 0;

		XQueryTree(dpy_,w,&root,&w,&children,&num);
		XFree(children);
	}


	in.advance();
	const char* v = in.getVerb();

	if(v == RETRIEVE)
	{
		const request   *s = in;
		const parameter *p = s->params;

		Cached url;

		while(p)
		{
			if(p->name[0] != '_')
			{
				Cached values;
				value * v = p->values;
				while(v)
				{
					if(values)  values = values + ";";
					values = values + v->name;
					v = v->next;
				}

				if(url) url = url + "/";
				url = url + p->name + "=" + values;
			}
			p = p->next;
		}

		if(url)
		{
			MvRequest r("WEBACCESS");
			r("URL") = catalogue_ + "/" + url;
			send(r,w);
		}
	}
	else if(v == WEBACCESS)
	{
		send(in,w);
	}
	else {
		MvRequest r("WEBACCESS");
		r("URL") = applications_ + "/" + v + ".html";
		send(r,w);
	}
}

int main(int argc,char **argv)
{
	MvApplication theApp(argc,argv);
	theApp.setFork(0);

	NormalAccess   web1;
	DropAccess     web2;

	theApp.run();
}
