// =====================================================================
//  $Id: TListCommand.cc,v 1.4 2004/03/07 10:30:28 goiwai Exp $
//  $Name: CLDAQ-1-14-06 $
//  $Log: TListCommand.cc,v $
//  Revision 1.4  2004/03/07 10:30:28  goiwai
//  ROOTに組みこむためのおまじないマクロを埋めこみました。
//  全てにおいて完全に動作するわけではありません。
//
//  Revision 1.3  2003/10/06 17:02:37  goiwai
//  *** empty log message ***
//
//  Revision 1.2  2003/07/30 16:17:31  goiwai
//  ファイルにコミットログをつけることにしました.
//
// =====================================================================
#include "TListCommand.hh"
#include "TRunManager.hh"
#include "TUserInterface.hh"
#include "TCommandTable.hh"

static const Tstring _name = "ls";
static const Tstring _desc = "list up.\nexample> ls\nexample> ls [command|directory]";

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

TListCommand::~TListCommand()
{;}

Tvoid TListCommand::Execute( const TstringList& arguments )
{
  if ( arguments.size() == 0 ) {
    normal();
  } else if ( arguments.size() == 1 ) {
    detail( arguments[ 0 ] );
  } else {
    Tcerr << "TListCommand::Execute: invalid arguments, " << Tendl;
    for ( Tsize_t i = 0; i < arguments.size(); i ++ ) {
      Tcerr << arguments[ i ];
      if ( i == arguments.size() - 1 ) {
	Tcerr << "." << Tendl;
      } else {
	Tcerr << ", ";
      }
    }
    ShowCommandDetail();
  }

  return;
}

Tvoid TListCommand::normal() const
{
  TUserInterface* ui = theRunManager -> GetUserInterface();
  if ( ui ) {
    Tint column = ui -> GetNumberOfColumns();
    Tstring cwd = ui -> GetCurrentWorkingDirectory();
    const TCommandTable& table = ui -> GetCommandTable();
    table.List( column, table.Sort( cwd ) );
  }
  return;
}

Tvoid TListCommand::detail( const Tstring& path ) const
{
  TUserInterface* ui = theRunManager -> GetUserInterface();
  if ( ui ) {
    Tstring abspath = ui -> ModifyPath( path );
    const TCommandTable& table = ui -> GetCommandTable();

    Tbool iscom = table.AlreadyExist( abspath );
    Tbool isdir = table.AlreadyExistDirectory( abspath );

    if ( iscom == Ttrue && isdir == Tfalse ) {
      TstringList args;
      args.push_back( abspath );
      ui -> ExecuteCommand( "help", args );
    } else if ( iscom == Tfalse && isdir == Ttrue ) {
      TstringList args;
      args.push_back( abspath );

      Tstring backdir = ui -> GetCurrentWorkingDirectory();

      ui -> ExecuteCommand( "cd", args );
      ui -> ExecuteCommand( "ls" );

      args.clear();
      args.push_back( backdir );
      ui -> ExecuteCommand( "cd", args );
    } else {
      ui -> NotFoundCommand( path );
    }

  }
  return;
}

#ifdef __CLDAQ_ROOT_DLL
    ClassImp(TListCommand)
#endif
