
#include "stdafx.h"

#ifndef _WIN32
#include <algorithm>
#endif

#ifdef _MSC_VER
#pragma warning(disable:4996) // deprecated stdlib names
#endif

#include "grt/grt_manager.h"

#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif


bec::GRTManager *grtm= 0;

void* get_mainwindow_impl()
{
  return 0;   
}

void write_message(const grt::Message &msg)
{
  printf("%s", msg.format().c_str());
  fflush(stdout);
}


std::string read_command(const char *prompt)
{
#ifdef USE_READLINE
  char *line= NULL;
  std::string tmp;

  line= readline(prompt);
  if (!line)
    return "";
  if (*line)
    add_history(line);

  tmp= line;
  g_free(line);

  return tmp + "\n";
#else
  char linebuf[1024];

  fputs(prompt, stdout);
  fflush(stdout);
  if (fgets(linebuf, sizeof(linebuf), stdin) <= 0)
    return "";
  return linebuf;
#endif
}

static char *compentry(const char *prefix, int i)
{
  static std::vector<std::string> entries;

  if (i == 0)
  {
    std::string word;
    entries= grtm->get_shell()->complete_line(prefix, word);
    return strdup(word.c_str());
  }
  else if (!entries.empty())
  {
    if (i < (int)entries.size())
    {
      return strdup(entries[i].c_str());
    }
  }
  return NULL;
}


void shell_ready(const std::string &prompt, std::string *prompt_var)
{
  *prompt_var= prompt;  
}

int main(int argc, char **argv)
{
  std::string prompt;

  grtm= new bec::GRTManager(false);
  
#ifdef USE_READLINE
  rl_completion_entry_function= compentry;
#endif

  grtm->set_message_callback(sigc::ptr_fun(write_message));

  grtm->set_search_paths("modules", "structs", "libraries");

  grtm->get_shell()->set_save_directory(".");
  
  grtm->get_shell()->set_ready_handler(sigc::bind<std::string*>(sigc::ptr_fun(shell_ready), &prompt));

  grtm->initialize();

  grtm->get_shell()->start();
  grtm->perform_idle_tasks();
  
  while (!grtm->terminated())
  {
    std::string line= read_command(prompt.c_str());
    if (line.empty())
      break;

    grtm->get_shell()->process_line_async(line);

    grtm->perform_idle_tasks();
  }
  grtm->get_shell()->write_line("Bye!");

  return 0;
}
