/*$cb
 *    This file is a part of libopenmhp.
 *
 *    Copyright (C) 2005 Mikko Novaro <miknov@gmail.com>
 *
 *    See main header file (libopenmhp/openmhp.h) for licensing and
 *    contact information.
 $ce*/

#ifndef XLETH
#define XLETH

#include <sys/types.h>
#include <stdio.h>
#include <list>
#include "event.hpp"

class cXlet {
private:
  FILE *clientToMhp;
  bool connected;
  int shmid; // shared memory segment id.
  int *shm;  // pointer to shared memory area.
  pthread_t read_thread;
  /* Registered event observers. Array of pointers to lists of
   * pointers to event observers ;) Length of the array is set by
   * EVENT_TYPE_CNT, and array indexes correspond to observable event
   * types (as in eEventType). */
  std::list <cXletEventObserver *> **observers;
  static cXlet *activeInstance; // TODO: pass through xlet->xmlhandler->xmlelement?

  char *name;
  char *path;
  char *xletClass;
  pid_t java_pid; // group ID of java processes. If not running, should be set to -1.
  void ExecuteJava(const char *virtualXServer, int virtualXDisplay,
		   const char *openmhpOutput);
  /* Connect to and disconnect from the java openmhp. */
  void Connect(void);
  void Disconnect(void);

public:
  cXlet(const char *Name, const char *Class, const char *Path);
  ~cXlet();

  static cXlet *GetActiveInstance(void); // TODO: pass through xlet->xmlhandler->xmlelement? ActiveInstance might be better, if there were more than one xlets. And besides, there's a communication channel for single xlet only.

  char *GetName(void);
  char *GetPath(void);
  char *GetClass(void);

  /* Starts the execution of the xlet. Returns after the execution if
     finished.*/
  void Start(const char *virtualXServer = "none",
	     int virtualXDisplay = 0,
	     const char *openmhpOutput = "discard");
  void Stop(void);

  int GetPixel(int x, int y, int layerIndex);
  void SendKeyEvent(int code); // TODO: generic "SendMessage(Message *)"

  /* Register xlet event observer to listen to events of a given type. */
  void RegisterObserver(eEventType type, cXletEventObserver *observer);

  /* The same single event object is passed to each observer. Event is
   * to be un-allocated by the original event source. */
  void NotifyEvent(eEventType type, const cXletEvent *event);
};

/* Parser for mhp AIT file data. */
class cXletFactory {
 private:
  FILE *pipe_handle;
 public:
  cXletFactory(char *mhpCacheDir, int channel);
  ~cXletFactory(void);
  /* Creates the next xlet. Returns NULL when all xlets have been
     created. */
  cXlet *Next(void);
};

#endif
