

#include <fosh/commander.h>
#include <fosh/command.h>
#include <stdio.h>         // printf
#include <lepto/log.h>

//#include <biwak/handler_freezer.cpp>

extern "C" {
   int ___printf(const char *format, ...)
   {
      int i1=0;
      while(format[i1])
      {
         putchar( format[i1++] );
      }
      return(i1);
   }
}

using namespace std;

CCommander::CCommander()
   :commandList( 7 /* List size */ )
{

};

#if 0
extern const createFuncType __start_commands asm("__start_commands");
extern const createFuncType __stop_commands  asm("__stop_commands");

int CCommander::registerCommands()
{
   const createFuncType *iter = &__start_commands;
   int count=0;

   // printf("Iters: \n");
   for ( ; iter < &__stop_commands; ++iter) {
      // printf("running func @%p @%p\n", iter, *iter);
      const CCommand *command=(*iter)();
      printf("created instance: %s\n", command->getName() );
      if(command)
         commandList += command;
      count++;
   }
   // printf("Iters done.\n");

   return( count );
}
#endif

int CCommander::execCommand( int argc, const char *argv[] )
{
   bool executed=false;
   int sta=-1;

   if(argc)
   {
      if(!strcmp(argv[0], "help"))
         return( printHelp() );

      // Empty command / line
      if( (!argv[0]) || (!argv[0][0]) )
         return( 0 );

      for (const CCommand *command : commandList)
      {
         //printf( "Check against '%s'.\n", command->getName() );
         if ( ! strcmp( argv[0], command->getName() ) )
         {
            sta=command->exec( argc, argv );
            executed=true;
         }
      }

      if( !executed )
      {
         fputs("Could not find command '", stdout);
         fputs(argv[0], stdout);
         fputs("'\n", stdout);
      }
   }
   return(sta);
}


int CCommander::printHelp()
{
   for (const CCommand *command : commandList)
   {
      command->printHelp(  );
   }

   return(0);
}


//---fin----------------------------------------------------------------------
