/***************************** 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 <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <Xm/Text.h>

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

#ifndef ScriptHelp_H
#include "ScriptHelp.h"
#endif

#ifndef Request_H
#include "Request.h"
#endif

#ifndef Parameter_H
#include "Parameter.h"
#endif

#ifndef HelpFactory_H
#include "HelpFactory.h"
#endif

#ifndef RequestPanel_H
#include "RequestPanel.h"
#endif

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

#ifndef XMLabel_H
#include "XMLabel.h"
#endif

ScriptHelp::ScriptHelp(Widget , RequestPanel& owner, const Parameter& def):
  gotInput_(false), RequestPanelHelp(owner, def),
  ShellTask((const char *)def.interfaceRequest()("help_script_command"),0)
{     
  Widget top = MetviewUI::root();
  create(XtDisplay(top),"Metview",0,0);
}


ScriptHelp::~ScriptHelp()
{
}

void ScriptHelp::start()
{
  XtRealizeWidget(xd_rootwidget());
  XMapRaised(XtDisplay(xd_rootwidget()),XtWindow(xd_rootwidget()));
  XMText text(text_);
  text.clear();
  
  XMLabel label(progressLabel_);
  label.set("Running external command ....");

  gotInput_ = false;
  attach(); 
  Object(currentObject_);
  ShellTask::start();
}

void ScriptHelp::ready(const char *line)
{
  static string cr = "\n";
  gotInput_ = true;
  XMText text(text_);
  text.append(line);
  text.append(cr);
}

void ScriptHelp::done(FILE *fp)
{
  XMLabel label(progressLabel_);
  if ( gotInput_ )
    label.set("External command finished.");
  else 
    label.set("External command produced no output. Check message window for errors");

  ShellTask::done(fp);
}

void ScriptHelp::closeCB(Widget,XtPointer)
{
  XUnmapWindow(XtDisplay(xd_rootwidget()),XtWindow(xd_rootwidget()));
}

static HelpMaker<ScriptHelp> maker("help_script");
