#include "sopnamsp.h"
#include "piacmdrdr.h"
#include <iostream> 
#include <unistd.h> 
#include <stdio.h> 

#ifdef WITH_GNUREADLINE
#include "readline/readline.h"
#include "readline/history.h"

PIACmdReader::PIACmdReader(PIStdImgApp* imgapp)
{
  cout << " PIACmdReader::PIACmdReader() Using GNU readline library " << endl;
  if (imgapp) _imgapp = imgapp;
  else throw NullPtrError("PIACmdReader::PIACmdReader(NULL) ! ");
}

void PIACmdReader::run()
{
  char * line = NULL;
  bool fgok = true;
  char prompt[128];
  int nc = 0;
  while (fgok) {
    usleep(100000);
    sprintf(prompt,"piapp[%d] ", nc);
    line = readline(prompt);
    if (!line) continue;
    else if (line[0] != '\0') {
      nc++;
      if (strcmp(line,"history") == 0) {
	cout << " ===> Command history ... " << endl;
	HIST_ENTRY **list;
	int i;
	list = history_list ();
	if (list)
	  for (int i = 0; list[i]; i++)
	    cout << i << "- " << list[i]->line << endl;
      }       
      else { 
	printf("[%d] %s\n", nc-1, line);
	string s = line;
	_imgapp->CmdInterpreter()->AddInputLine(s);
	add_history (line);
      }
    }
    free(line); 
  }
}
#else
//  ------ SANS GNU readline --------
PIACmdReader::PIACmdReader(PIStdImgApp* imgapp)
{
  cout << " PIACmdReader::PIACmdReader() Using fgets() - without GNU readline " << endl;
  if (imgapp) _imgapp = imgapp;
  else throw NullPtrError("PIACmdReader::PIACmdReader(NULL) ! ");
}

void PIACmdReader::run()
{
  char line[1024];
  bool fgok = true;
  int nc = 0;
  while (fgok) {
    usleep(100000);
    printf("piapp[%d] ", nc);
    line[0] = '\0';
    char* rs = fgets(line, 1024, stdin);
    if (rs == NULL) continue;
    int l = strlen(line);
    if (l < 1)  continue; 
    if ( (line[l-1] == '\n') || (line[l-1] == '\r') )  line[l-1] = '\0';
    if (line[0] != '\0') {
      printf("[%d] %s\n", nc, line);
      nc++;
      string s = line;
      _imgapp->CmdInterpreter()->AddInputLine(s);
    }
  }
}

#endif

