/***************************** 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

#include <Xm/Text.h>

#ifndef Path_H
#include "Path.h"
#endif


XMText::XMText(Widget text):
	text_(text)
{
}

XMText::~XMText()
{
}

void XMText::load(const Path& path,bool include)
{
	string s = path.loadText();
	if(include)
		insert(s);
	else
		set(s);
}

void XMText::save(const Path& path)
{
	path.saveText(get());
}

void XMText::insert(const string& s,bool select)
{
	XmTextPosition	from,to;

	XmTextGetSelectionPosition(text_,&from,&to);
	if(from == to) from = to = XmTextGetInsertionPosition(text_);
	XmTextReplace(text_,from,to,(char*)s.c_str());
	if(select)
		XmTextSetSelection(text_,from,from+s.length(),CurrentTime);
	else
		XmTextSetSelection(text_,from+s.length(),
			from+s.length(),CurrentTime);
	XmTextSetInsertionPosition(text_,from+s.length());
}

string XMText::get()
{
	char* p = XmTextGetString(text_);
	string s = p;
	XtFree(p);
	return s;
}

void XMText::set(const string& s)
{
	XmTextSetString(text_,(char*)s.c_str());
}

void XMText::clear()
{
	XmTextSetString(text_,"");
}

void XMText::append(const string& s)
{
	moveToEnd();
	insert(s);
	moveToEnd();
}

void XMText::moveToEnd()
{
	XmTextPosition pos = XmTextGetLastPosition(text_);
	XmTextSetInsertionPosition(text_,pos);
	XmTextSetSelection(text_,pos,pos,CurrentTime);
	XmTextShowPosition(text_,pos);
}


void XMText::selectLine(int line)
{
	char *p              = XmTextGetString(text_);
	char *q              = p;
	XmTextPosition start = 0;
	XmTextPosition end   = XmTextGetLastPosition(text_);
	int    n             = 0;

	if(line<=0) line = 1;

	while(*p)
	{
		if(*p == '\n') 
		{ 
			n++;
			if(n == line)  
			{
				end = p - q;
				break;
			}
			start = p - q + 1;
		}
		p++;
	}

	XmTextSetSelection(text_,start,end,CurrentTime);
	XmTextShowPosition(text_,start);

	XtFree((char*)q);
}

void XMText::set(double x)
{
	char buf[80];
	sprintf(buf,"%g",x);
	set(buf);
}

void XMText::get(double& x)
{
	x = atof(get().c_str());
}
