#define POLL
#include "ivrun.h"
#include <Dispatch/iohandler.h>
#include <Dispatch/dispatcher.h>
#include <InterViews/session.h>
#ifdef POLL
#include <InterViews/event.h>
#endif
#include "types.h"
#include "exceptions.h"

// Some of the code and ideas here (e.g. the input and event handling)
// are based on the OC interpreter, by Michael Hines,
// Neurobiology Dept., DUMC, Durham, NC. hines@neuro.duke.edu


Session *MySession = 0;
int HaveInterViews = 1;

class HandleStdin: public IOHandler
{
public:
  HandleStdin() { stdinSeen_ = false; acceptInput_ = true; }
  virtual int inputReady(int fd);
  virtual int  exceptionRaised(int fd);
  boolean stdinSeen_;
  boolean acceptInput_; 
};

int HandleStdin::inputReady(int fd)
{
  if(fd); // ??? FIXME
  stdinSeen_ = 1;
  if (acceptInput_) {
    MySession->quit();
  }
  return 0;
}

int HandleStdin::exceptionRaised(int fd)
{
  // hoc_interviews = 0;
  if(fd); // ??? FIXME
  stdinSeen_ = 1;
  MySession->quit();
  return 0;
}

HandleStdin *StdinHandler = 0;

int run_til_stdin ()
{
#ifdef POLL
  Event e;
#if 1
  if (MySession->read(0, 30, e))
    e.handle();
#else
  if (MySession->pending()) {
    MySession->read(e);
    e.handle();
  }
#endif
#else
  StdinHandler->stdinSeen_ = 0;
  MySession->run();
#endif
//  WinDismiss::dismiss_defer();	// in case window was dismissed
#ifdef POLL
  return 0;
#else
  return StdinHandler->stdinSeen_;
#endif
}

void
My_IV_init(int argc, char **argv)
{
  if (getenv("DISPLAY") == 0)
    {
      MySession = 0;
      HaveInterViews = 0;
      return;
    }
  MySession = new Session("Q", argc, argv, 0, 0);

  StdinHandler = new HandleStdin;
#ifndef POLL
  Dispatcher::instance().link(0, Dispatcher::ReadMask, StdinHandler);
  Dispatcher::instance().link(0, Dispatcher::ExceptMask, StdinHandler);
#endif
}

void set_rl_event_hook (int on_off)
{
  if (on_off)
    rl_event_hook = run_til_stdin;
  else
    rl_event_hook = 0;
}

volatile void signal_no_display()
{
  Signal(new GenericCondition("No DISPLAY variable (not running under X?)."));
}
