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

#ifndef ComputeEditor_H
#include "ComputeEditor.h"
#endif

#ifndef EditorFactory_H
#include "EditorFactory.h"
#endif

#ifndef IconObject_H
#include "IconObject.h"
#endif

#ifndef Log_H
#include "Log.h"
#endif

#ifndef Request_H
#include "Request.h"
#endif
#include <ctype.h>


ComputeEditor::ComputeEditor(const IconClass& name,const string& kind):
	BaseTextEditor(name,kind)
{
}

ComputeEditor::~ComputeEditor()
{
}

void ComputeEditor::apply()
{
	XMText text(text_);
	Request r("COMPUTE");	
	string  f  = text.get();

	r("FORMULA") = f.c_str();
	r.save(current_->path());

}

void ComputeEditor::reset()
{
	Request r  = current_->request();
	const char* f  = r("FORMULA");

	XMText text(text_);
	text.set(f?f:"");

	modified_ = false;
}

void ComputeEditor::close()
{
	XMText text(text_);
	text.clear();
}

void ComputeEditor::merge(IconObject* o)
{
	XMText text(text_);

	string s = current_->relativeName(o);
	bool quote = false;


	//for(string::iterator i = s.begin(); i != s.end(); ++i)
	for(int it=0; it<s.length(); ++it)
	{
		//if(i == s.begin() &&  *i != '_' && !isalpha(*i)) quote = true;
		if(it == 0 &&  s[it] != '_' && !isalpha(s[it]))
			quote = true;

		//if(*i != '_' && !isalnum(*i)) quote = true;
   		if(s[it] != '_' && !isalnum(s[it])) 
			quote = true;
	}


	if(quote) 
		s = string("\'") + s + string("\'");
	text.insert(s);
}

void ComputeEditor::replace(IconObject* o)
{
	
}


static EditorMaker<ComputeEditor> editorMaker("ComputeEditor");

