// =====================================================================
//  $Id: TExecuteCommand.cc,v 1.1.1.1 2003/06/27 02:56:41 goiwai Exp $
//  $Name: CLDAQ-1-06-02 $
// =====================================================================
#include "TExecuteCommand.hh"
#include "TRunManager.hh"
#include "TUserInterface.hh"

static const Tstring _name = "/system/execute";
static const Tstring _desc = "read a macro file, execute.\n1st argument is filename, 2nd argument(omiitable) is a number of loop, you wish.\nexample> /system/execute sample.macro\nexample> /system/execute sample.macro 100";

TExecuteCommand::TExecuteCommand( TRunManager* manager )
  : TCommand( manager, _name, _desc ), theMacroFileParser()
{;}

TExecuteCommand::~TExecuteCommand()
{;}

Tvoid TExecuteCommand::Execute( const TstringList& arguments )
{
  TUserInterface* ui = theRunManager -> GetUserInterface();
  static const Tstring head = "TExecuteCommand::Execute: ";

  if ( ui ) {
    if ( arguments.empty() ) {
      ShowCommandDetail();
    } else if ( arguments.size() == 1 ) {
      Tstring filename = arguments[ 0 ];
      doExecute( ui, filename );
    } else if ( arguments.size() == 2 ) {
      Tstring filename = arguments[ 0 ];
      Tint nloop = strtol( arguments[ 1 ].c_str(), 0, 0 );
      doExecute( ui, filename, nloop );
    } else {
      Tcerr << head << "number of arguments should be 1 or 2." << Tendl;
      ShowCommandDetail();
    }
  } else {
    Tcerr << head << "UserInterface doesn't exist." << Tendl;
  }
  return;
}

Tvoid TExecuteCommand::doExecute( TUserInterface* ui, const Tstring& filename, Tint nloop )
{
  theMacroFileParser.SetMacroFileName( filename );
  TstringList readbuf;

  for ( Tint i = 0; i < nloop; i ++ ) {
    theMacroFileParser.Open();
    while ( theMacroFileParser.IsSuccess() ) {
      readbuf = theMacroFileParser.ReadLine();
      if ( theMacroFileParser.IsExecutable( readbuf ) ) {
	Tstring command = theMacroFileParser.GetCommand( readbuf );
	TstringList args = theMacroFileParser.GetArguments( readbuf );
	ui -> ExecuteCommand( command, args );
      }
    }
    theMacroFileParser.Close();
  }

  return;
}
