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

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

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

MacroParamObject::~MacroParamObject()
{
}

void MacroParamObject::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* MacroParamObject::state() const
{
	MacroParamObject* self = const_cast<MacroParamObject*>(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& MacroParamObject::language() const
{
    return state()->iconClass().language();
}

Request MacroParamObject::fullRequest() const
{
    Request r = StandardObject::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;
    
    s.print();
    r.print();
    
    return s + r;
}

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

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

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


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