/***************************** 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 "MacroParamState.h"
#include "MacroGuiObject.h"
//#include "Log.h"
#include "IconFactory.h"

MacroParamState::MacroParamState(IconObject* o,IconObject* m,const Request& r):
	owner_(o),
	macro_(m),
	request_("MACROPARAM"),
	class_(0)
{
	request_.mars_merge(r);
}

MacroParamState::~MacroParamState()
{
	delete class_;
}

IconObject* MacroParamState::macro() const
{
	return macro_;
}

Request MacroParamState::request() const
{
	return temp_ ? temp_->request() : request_;
}

void MacroParamState::request(const Request& r)
{
	request_ = r;
	temp_ = 0;
}

IconObject* MacroParamState::iconObject()
{
	if(!temp_)
		temp_ = IconFactory::createTemporary(owner_,request_,&iconClass());

	return temp_;
}

void MacroParamState::macro(IconObject* macro)
{
	if(macro_ != macro)
		macro_ = macro;

	temp_  = 0;
	delete class_;
	class_ = 0;
}


Request MacroParamState::interface() const
{
	Action action("edit","*");
	MvRequest r   = requests();



	r("_NAME")    = owner_->fullName().c_str();
	r("_CLASS")   = owner_->iconClass().name().c_str();
	r("_ACTION")  = "edit";
	r("_SERVICE") = "macro";

	r.print();

	int error;
	Request result = MvApplication::waitService("macro",r,error);

	result.print();
	return result;

}

Request MacroParamState::requests() const
{
	if(!macro_)
	{
		//Log::error(owner_) << "Missing macro icon" << endl;
		return Request("");
	}

	Request r("MACROPARAM");
	r("MACRO") = macro_->fullRequest();

	return r + request_;
}

const IconClass& MacroParamState::iconClass()
{
    if(!class_)
    {
        Request i = interface();
        class_ = new MacroGuiObject(i,&owner_->iconClass());
    }
    return *class_;
}


