/***************************** 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 <string>
using std::string;

#include "Metview.h"
#include "EditTransaction.h"
#include "IconObject.h"
#include "Request.h"
#include "Task.h"
#include "Folder.h"
#include "IconFactory.h"
#include "EditorObserver.h"
#include "Editor.h"
#include "Folder.h"

#ifndef Protocol_H
#include "Protocol.h"
#endif
#ifndef TempIconClass_H
#include "TempIconClass.h"
#endif

#ifndef Action_H
#include "Action.h"
#endif
EditTransaction::EditTransaction(): 
	Transaction("EDIT") 
{ 
}

EditTransaction::~EditTransaction()
{ 
	//delete subClass_;
}

EditTransaction::EditTransaction(MvTransaction* t) :
	Transaction(t)
{
}

MvTransaction *EditTransaction::cloneSelf()
{ 
	return new EditTransaction(this); 
}

void EditTransaction::apply(IconObject*)
{
	Task* task = current_->action(Action("prepare"));
	task->add(this);
}

void EditTransaction::close(IconObject*)
{
	setError(1,"Edit canceled");
	sendReply(MvRequest());
}

void EditTransaction::success(Task*,const Request& r)
{
	sendReply(r);
}

void EditTransaction::failure(Task*)
{
	setError(1,"Edit canceled");
	sendReply(MvRequest());
}

void EditTransaction::callback(MvRequest& r)
{

	r.print();

    current_ = 0;

	MvRequest def = r("DEFINITION");

	if ( def ) 
	{
		const char* name = def("_NAME");
		if ( name ) 
	      	current_ = IconObject::search(name);

	    if ( !current_ )
			current_ = IconFactory::create(Folder::folder("temporary"),def);
	}

	else 
	{
		r.advance();

		if ( r )
		{
			subClass_ = new TempIconClass(r);
			Request t(subClass_->name().c_str());
			current_ = IconFactory::create(Folder::folder("temporary"),t);
		}

		else 
		{
			close(current_);
			return;
		}
			
	}

	current_->edit();

	Editor* e = current_->editor();
	e->observer(this);
	e->temporary();


}



static ProtocolFactory<EditTransaction> edit;

