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

#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <Tab.h>
#include <Xm/ToggleB.h>
#include <Xm/Text.h>


#ifndef LogWindow_H
#include "LogWindow.h"
#endif

#ifndef MetviewUI_H
#include "MetviewUI.h"
#endif

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


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

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

#ifndef XMText_H
#include "XMText.h"
#endif


typedef set<LogWindow*> Set;
static Set windows;


LogWindow::LogWindow():
	Timeout(1),
	current_(0),
	file_(0)
{
	Widget top = MetviewUI::root();
	create(XtDisplay(top),"Metview",0,0);
	windows.insert(this);
}

LogWindow::~LogWindow()
{
	// Not called

	//if(current_) current_->detach();
	//XtDestroyWidget(xd_rootwidget());
	//

}

void LogWindow::open(IconObject* icon)
{
	LogWindow *e = icon->logWindow();
	if(e == 0)
	{
		for(Set::iterator j = windows.begin(); j != windows.end(); ++j)
			if((*j)->current_ == 0)
				e = (*j);

		if(e == 0) e = new LogWindow();

	}
	e->show(icon);
}

void LogWindow::show(IconObject* icon)
{
	if(icon != current_)
	{
		current_ = icon;	
		if(current_) {
			current_->logWindow(this);
			XtVaSetValues(xd_rootwidget(),XmNtitle, current_->name().c_str(), 0);
			load();
		}
	}
	raise();
}

void LogWindow::load()
{
	stop();
	if(file_) {
		fclose(file_);
		file_ = 0;
	}

	Path p = current_->logPath();

	XMText text(text_);
	text.load(p);

	file_   = fopen(p.str().c_str(),"r");
	if(file_)
	{
		fseek(file_,0,SEEK_END);
		start(file_);
	}
}

void LogWindow::raise()
{
	XtRealizeWidget(xd_rootwidget());
	XMapRaised(XtDisplay(xd_rootwidget()),XtWindow(xd_rootwidget()));
}	

void LogWindow::closeCB(Widget,XtPointer)
{
	close();
}

void LogWindow::close()
{
	if(file_)
	{
		fclose(file_);
		file_ = 0;
	}

	stop();

	XMText text(text_);
	text.clear();

	if(current_) current_->logWindow(0);
	current_ = 0;
	XUnmapWindow(XtDisplay(xd_rootwidget()),XtWindow(xd_rootwidget()));
}

void LogWindow::done(FILE*)
{
	stop();
	enable();
}

void LogWindow::run()
{
	start(file_);
	disable();
}

void LogWindow::ready(const char* l)
{
	static string cr = "\n";
	XMText text(text_);
	text.append(l);
	text.append(cr);
}

void LogWindow::clearCB(Widget,XtPointer)
{
	Path p  = current_->logPath();
	FILE *f = fopen(p.str().c_str(),"w");
	if(f) fclose(f);

	load();
}

void LogWindow::freezeCB(Widget,XtPointer data)
{
	XmToggleButtonCallbackStruct* cb = (XmToggleButtonCallbackStruct*)data;
	if(cb->set) 
		stop();
	else 
		load();
}
