/***************************** 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 <Xm/PushB.h>
#include "Recents.h"
#include "Resources.h"
#include "Folder.h"

static set<Recents*> all;
static list<string> recent;

Recents::Recents():
	fixed_(0),
	widget_(0)
{

	if(all.size() == 0)
		Resources::get("RECENT",recent);

	all.insert(this);
}

Recents::~Recents()
{
	all.erase(this);

	if(all.size() == 0)
		Resources::set("RECENT",recent);
}

void Recents::top(Folder* f)             
{
	string name = f->fullName();
	if(name == "")
	   name = "/";

	for(set<Recents*>::iterator j = all.begin(); j != all.end(); ++j)
		(*j)->top(name);

	list<string>::iterator k = find(recent.begin(),recent.end(),name);

	if(k != recent.end())
	   recent.erase(k);

	recent.push_front(name);

	while(recent.size() > 15)
		remove(recent.back());

}

void Recents::open(const char* n)
{
	Folder* f = Folder::folder(n,false);
	if(f != 0)
	{
		top(f);
		f->open();
	}
	else
		remove(n);

}

void Recents::remove(const string& name)
{
	const char* n = name.c_str();

	list<string>::iterator k = find(recent.begin(),recent.end(),name);

	if(k != recent.end())
	   recent.erase(k);

	for(set<Recents*>::iterator j = all.begin(); j != all.end(); ++j)
	{
		Widget w = XtNameToWidget((*j)->widget_,n);     
		if(w != 0)
		   XtDestroyWidget(w);
	}
	
}

void Recents::install(Widget w)      
{
	widget_ = w;
	XtVaGetValues(w,XmNnumChildren,&fixed_,0);

	for(list<string>::iterator j = recent.begin(); j != recent.end(); ++j)
		add(*j);
}

Widget Recents::add(const string& name)
{
	const char* n = name.c_str();
	Widget w = XtNameToWidget(widget_,n);               
	if(w == 0)
	   w = XmCreatePushButton(widget_,(char*)n,0,0);
	XtManageChild(w);
	return w;
}

void Recents::top(const string& name)
{
	short pos;
	Widget w = add(name);
	XtVaGetValues(w,XmNpositionIndex,&pos,0);
	if(pos >= fixed_)
		XtVaSetValues(w,XmNpositionIndex,(short)fixed_,0);      
}
