/***************************** 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 "FamilyScanner.h"

#include "IconClass.h"

static map<string, FamilyScanner*> cache;


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

    return *(new FamilyScanner(kind));
}


FamilyScanner::FamilyScanner(const IconClass& kind) :
    class_(kind)
{
    //cout << "FamilyScanner " << kind.name() << endl;

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

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

FamilyScanner::~FamilyScanner()
{
}

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

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

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

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

void FamilyScanner::next(const MvIconParameter& 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& FamilyScanner::keyword() const
{
    return keyword_;
}

bool FamilyScanner::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 << "FamilyScanner::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 << "FamilyScanner::validate -> " << endl;
		r.print();
		r = f + Request( p );
		r.print();
		cout << "<- FamilyScanner::validate " << endl;
		return true;
	}

#endif
    return false;
}
