/***************************** 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 MacroParam_H
#include "MacroParam.h"
#endif

#include "IconFactory.h"
#include "IconClass.h"

MacroParam::MacroParam(Folder* parent,const IconClass& kind,
	const string& name,IconInfo* info):
	Basic(parent,kind,name,info)
{
}

MacroParam::~MacroParam()
{
}

void MacroParam::state(MacroParamState* state)
{
	IconObjectH macro = state->macro();

	Request r("MACROPARAM");
	if(macro)
		r("MACRO") = relativeName(macro).c_str();

	r = r + state->request();

	r.save(path());
}

MacroParamState* MacroParam::state() const
{
	MacroParam* self = const_cast<MacroParam*>(this);
	//if(state_ == 0)
	{
	    IconObject* macro = 0;

	    Request r(path());
	    const char *name = r("MACRO");
	    if(name)
	    {
		string fullName  = makeFullName(name);
		macro =  IconObject::search(fullName);
	    }

	    self->state_ = new MacroParamState(self,macro,r.advance());
	}

	return state_;
}

Language& MacroParam::language() const
{
    return state()->iconClass().language();
}

Request MacroParam::fullRequest() const
{
    Request r = Basic::fullRequest();

    Request s(path());
    const char *name = s("MACRO");
    if(name) {
	string fullName  = makeFullName(name);
	IconObject* macro =  IconObject::search(fullName);
	if(macro)
		s("MACRO") = macro->request();
    }


    s =  s.justOneRequest() + r;
    return s + r;
}

Request MacroParam::request() const
{
    Request r(path());
    r.advance();

    // For compatibility with old stuff
    Request s(iconClass().name());
    s.mars_merge(r);
    return s;
}

void MacroParam::request(const Request& r)
{
    Request s(path());
    s =  s.justOneRequest() + r;
    s.save(path());
}


static IconMaker<MacroParam> maker("MACROPARAM");
