/***************************** 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 <functional>  // ptr_fun()
#include <algorithm>   // algorithm()
#include <cstdlib>

#ifndef CatalogDrawer_H
#include "CatalogDrawer.h"
#endif

#ifndef EditorDrawerFactory_H
#include "EditorDrawerFactory.h"
#endif

#ifndef RetrieveEditor_H
#include "RetrieveEditor.h"
#endif

#ifndef Netscape_H
#include "Netscape.h"
#endif

#ifndef XMLabel_H
#include "XMLabel.h"
#endif

#ifndef Folder_H
#include "Folder.h"
#endif

#ifndef IconFactory_H
#include "IconFactory.h"
#endif

CatalogDrawer::CatalogDrawer(RetrieveEditor& e):
	XEditorDrawer<UICatalogDrawer_c>(e),
	editor_(e)
{
}

CatalogDrawer::~CatalogDrawer()
{
}

void CatalogDrawer::topCatalogCB(Widget,XtPointer)
{
	Netscape::showPage("catalogue");
}

void CatalogDrawer::homeCB(Widget,XtPointer)
{
	Netscape::showPage("webmars");
}

void CatalogDrawer::inCatalogCB(Widget,XtPointer)
{
//-- NOTE:
//-- It looks like that here we should use the ecmwf.def language file
//-- and tell the editor to expand the last value (EXPAND_LAST_NAME)
//-- and not the default second last (EXPAND_2ND_NAME)...
//-- ('stream=da' does not work, but 'stream=oper' does!)
//--
	Request r = editor_.currentRequest(EXPAND_LAST_NAME);
	const request   *s = r;
	const parameter *p = s->params;

	string url;

	while(p)
	{
		if(p->name[0] != '_')
		{
			vector<string> v = r.get(p->name);

			string values;
			for(int i = 0 ; i < v.size() ; i++)
			{
				if(i) values = values + ';';
				 values = values + v[i];
			}

			if(v.size())
			{
				//-- also, convert to lower case --
				if(url.length()) url = url + "/";
				transform( values.begin(), values.end()
				         , values.begin(), std::ptr_fun ( tolower ) );
				string pname = p->name;
				transform( pname.begin(), pname.end()
				         , pname.begin(), std::ptr_fun ( tolower ) );
				url = url + pname + '=' + values;
			}
		}

		p = p->next;
	}

	Netscape::showPage("catalogue",url);
}

void CatalogDrawer::helpCB(Widget,XtPointer)
{
	Netscape::showPage("catalogue_help");
}

void CatalogDrawer::grabCatalogCB(Widget,XtPointer)
{

	Netscape::showURL("javascript:new MetviewGrab");

	XMLabel message(message_);
	message.set("");

	Path path(::marstmp());
	path.remove();  // If the file exists, netscape will open a dialog
	Netscape::savePage(path);

	int i = 0;
	while(i++ < 20 && !path.exists())
		sleep(1);

	if(!path.exists())
	{
		message.set("Web browser did not respond in time");
		return;
	}

	Folder* temp = Folder::folder("temporary");
	string name = temp->uniqueName("Catalog");
	Path p = temp->path().add(name);


	bool ok = false;
	FILE* f = fopen(path.str().c_str(),"r");
	FILE* g = fopen(p.str().c_str(),"w");

	if(f && g)
	{
		char line[10240];
		bool out = false;
		while(fgets(line,sizeof(line),f))
		{
			if(out)
			{
				if(strcmp(line,"-->\n") == 0)
					break;

				ok = true;
				fputs(line,g);
			}
			else {
				if(strcmp(line,"<!--Metview\n") == 0)
					out = true;
			}
		}
	}

	if(f) fclose(f);
	if(g) fclose(g);

	if(!ok)
		message.set("Could not find useful information in this page");
	else
	{
		message.set("Grab successful");
		IconObjectH o =  IconFactory::create(Folder::folder("temporary"),name);
		editor_.merge(o);
	}

}

static EditorDrawerMaker<CatalogDrawer,RetrieveEditor> maker(10);
