/* zprstat.c */

/*--------------------------------------------------------------------------*/

#include <stdio.h>
#include "common.h"
#include <sys/types.h>
#if defined(_AIX) && defined(_IBMR2)
#include <sys/select.h>
#endif
#include <X11/Intrinsic.h>
#include <zephyr/zephyr.h>
#include "zprstat.h"
#include "Prntr.h"
#include "Notice.h"
#include "Window.h"

/*--------------------------------------------------------------------------*/

char*	program_name;
Bool    debug = FALSE;
char*	empty_string = "";

static	char	buffer[1024];
static	char*	filenames[] =
{
    NULL,
    "/mit/consult/lib/zprstat/all.printers",
    NULL,
};
static	char*	zprstat_class = "ZPRSTAT";
static	char*	zprstat_instance = "UPDATE";
static	char*	printer_class = "PRINTER";
static	char*	recipient_all = "*";
static	Bool	wg_subscribe = FALSE;

/*--------------------------------------------------------------------------*/

void	main(argc, argv)
int	argc;
char*	argv[];
{
    int i;
    Prntr* printers;
    Prntr* p;
    char* msg;
    int z_fd;
    int x_fd;
    fd_set read_fds;
    fd_set all_fds;
    int num_fds;
    int n;

    sprintf(buffer, "%s/.printers", getenv("HOME"));
    filenames[0] = NewString(buffer);

    for (i = 1; i < argc; i++)
      {
	  if ((strcmp(argv[i], "-s") == 0) ||
	      (strcmp(argv[i], "-sub") == 0))
	    {
		wg_subscribe = TRUE;
		continue;
	    }
      }

    program_name = argv[0];

    z_fd = Notice_Initialize(TRUE);
    printers = Prntr_Initialize(filenames);

    Notice_Subscribe(zprstat_class, zprstat_instance, recipient_all, FALSE);

    if (wg_subscribe)
      for (p = printers; p != NULL; p = Prntr_Next(p))
	Notice_Subscribe(printer_class, Prntr_Name(p), recipient_all, TRUE);

    x_fd = Window_Initialize(&argc, argv, printers);

    num_fds = max(x_fd, z_fd) + 1;

    FD_ZERO(&all_fds);
    FD_SET(x_fd, &all_fds);
    FD_SET(z_fd, &all_fds);

    setpriority(0 /*PRIO_PROCESS*/, 0, 15);

    forever
      {
	  read_fds = all_fds;

	  while (ZPending() || XtPending())
	    {
		if (ZPending())
		  {
		      msg = Notice_Receive(zprstat_class, zprstat_instance);
		      Window_Update(msg, printers);
		      Delete(msg);
		  }
		if (XtPending())
		  Window_Event();
	    }

	  n = select(num_fds, &read_fds, NULL, NULL, NULL);

	  Window_Ping();

	  if (n == -1)
	    {
		fprintf(stderr, "Error on select\n");
		exit(1);
	    }

	  if (FD_ISSET(z_fd, &read_fds) && ZPending())
	    {
		msg = Notice_Receive(zprstat_class, zprstat_instance);
		Window_Update(msg, printers);
		Delete(msg);
	    }

	  if (FD_ISSET(x_fd, &read_fds))
	    if (XtPending())
	      Window_Event();
	    else
	      exit(0);
      }
}

/*--------------------------------------------------------------------------*/
