/***************************** 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 *************************************/


#ifndef FamilyHelper_H
#include "FamilyHelper.h"
#endif

#ifndef IconClass_H
#include "IconClass.h"
#endif

static map<string,FamilyHelper*> cache;


FamilyHelper& FamilyHelper::find(const IconClass& kind)
{
     map<string,FamilyHelper*>::iterator j = cache.find(kind.name());
     if(j != cache.end())
        return *(*j).second;

     return *(new FamilyHelper(kind));
}
 

FamilyHelper::FamilyHelper(const IconClass& kind):
	class_(kind)
{	

	cout << "FamilyHelper " << kind.name() << endl;

	kind.language().scan(*this);
	keyword_ = kind.language().getInfo();
	if(keyword_ == "") keyword_ = "_SECOND_GROUP";

	cache[kind.name()] = this;
}

FamilyHelper::~FamilyHelper()
{
}

void FamilyHelper::next(const Parameter& param)
{
	params_.push_back(param.name());
	param.scan(*this);
}

const vector<string>& FamilyHelper::params() const
{
	cout << "FamilyHelper parans " << params_.size() << endl;
	return params_; 
}

const vector<string>& FamilyHelper::values(const string& s) // const
{
	return values_[s]; 
}

const vector<string>& FamilyHelper::beau(const string& s) // const
{
	return beau_[s]; 
}

void FamilyHelper::next(const Parameter& p, const char* first,const char* second)
{
	const char* type = (second) ? second : first;
	values_[p.name()].push_back(type);
	beau_[p.name()].push_back(p.beautifiedName(first));
	names_[type]    = type;
}


const string& FamilyHelper::keyword() const
{
	return keyword_;
}

bool FamilyHelper::validate(Request& r) const
{
	Request s = r;
	s.advance();
	if(!s) {

		if(!r) r = Request(class_.name());

		Request f = class_.language().expand(r.justOneRequest(), 
			EXPAND_2ND_NAME);

		const char* p = f(keyword_.c_str());
		r = f + Request( p );
		return true;


	}
#if 0
	cout << "FamilyHelper::validate -> " << endl;
	r.print();

	Request f = class_.language().expand(s.justOneRequest(), EXPAND_2ND_NAME);
	f.print();

	if(!f || !f.getVerb() || class_.name() != f.getVerb())
	{
		r = Request(class_.name().c_str());
		validate(r);
		return true;
	}

	const char* v = s.getVerb();
	const char* p = f(keyword_.c_str());

	if(!v || /*names_.find(v) == names_.end() ||*/ v != p)
	{
		cout << "FamilyHelper::validate -> " << endl;
		r.print();
		r = f + Request( p );
		r.print();
		cout << "<- FamilyHelper::validate " << endl;
		return true;
	}

#endif
	return false;
	
}


