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

 Copyright 2014 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 "Items.h"

#include "ConfigLoader.h"
#include "Folder.h"
#include "IconClass.h"
#include "IconObject.h"
#include "IconFactory.h"
#include "Log.h"
#include "Request.h"

static map<string,Items*> items;

Items::Items(request* r):
	r_(r),
	object_(0)
{
	items[get_value(r,"name",0)] = this;
}

Items::~Items()
{
}

void Items::load(request* r)
{
  	new Items(r);
}

void Items::createAll()
{  
        for(map<string,Items*>::iterator it = items.begin() ; it != items.end(); it++)
	{
	  	it->second->object();
	}	
}  

void Items::objects(vector<IconObject*> &ret)
{
	for(map<string,Items*>::iterator it = items.begin() ; it != items.end(); it++)
	{
	  	if(it->second->object())
		  	ret.push_back(it->second->object());
	}
}	

IconObject* Items::find(const string& a)
{
	// cout << "Items::find( " << a << endl;
	map<string,Items*>::iterator j = items.find(a);
	if(j == items.end())
		return 0;
	else
		return (*j).second->object();
}
 
IconObject* Items::object()
{
	if(object_ != 0)
		return object_;
	
	const char *kind = get_value(r_,"class",0);
	const char *full = get_value(r_,"full_name",0);
	//const char *x    = get_value(r_,"x",0);
	//const char *y    = get_value(r_,"y",0);
	const char *link = get_value(r_,"linked_to",0);
	
	object_ = IconObject::search(full); 
	if(object_) return object_;

	if(link)
	{
		Path path = Folder::top()->path();
		path = path.add(full);
		path.symlink(string(link));
	}

	
	object_ = IconFactory::create(full,IconClass::find(kind));
	/*if(object_) {
		if(x && y) object_->parent()->position(object_,atol(x),atol(y));
		return object_;
	}*/

	return object_;
	
	Log::error(0) << "Cannot create " << full << endl;
	return 0;
}
 
  		
static SimpleLoader<Items> loadClasses("special_folder",1);
