// simple example program for cdev client to monitor cdev servers

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <rsvcClient.h>

static void getServerCallback (int status, void* /* arg */, rsvcData* data)
{
  if (status == RSVC_SUCCESS) {
    printf ("Get server success\n");
    data->asciiDump ();
  }
  else
    printf ("cannot get server info\n");
}

static void qcallback (int status, void* /* arg */, rsvcData* data)
{
  printf ("---------------------Query callback is called\n");
  if (status == RSVC_INCOMPLETE) {
    printf ("Single data entry is here\n");
    data->asciiDump ();
  }
  else if (status == RSVC_SUCCESS) {
    printf ("Query finished\n");
    data->asciiDump ();
  }
  else
    printf ("Query error\n");
  printf ("---------------------Query finished\n");
}

static void monitorServerCallback (int status, void* /* arg */, rsvcData* data)
{
  if (status == RSVC_SUCCESS) {
    printf (">>>>>>>>>>monitor server callback called<<<<<<<<<<<<<<<<\n");
    data->asciiDump ();
    printf ("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
  }
  else if (status == RSVC_CBK_FINISHED) {
    printf ("server has been deleted\n");
  }
  else 
    printf ("server monitor callback has status %d\n", status);
}

int main (int argc, char** argv)
{
  if (argc < 4) {
    fprintf (stderr, "Usage: %s servername domain rsvcserverhost rsvcserverport\n");
    exit (1);
  }

  rsvcClient client;
  if (client.connect (argv[3], atoi (argv[4])) != RSVC_SUCCESS) {
    fprintf (stderr, "cannot connect to rsvc server\n");
    exit (1);
  }

  rsvcData serverinfo;
  serverinfo.insert ("name", argv[1]);
  serverinfo.insert ("domain", argv[2]);
  if (client.getValue ("cdevServers", serverinfo,
		       getServerCallback, 0) != RSVC_SUCCESS) {
    fprintf (stderr, "cannot get server %s %s information\n",
	     argv[1], argv[2]);
    exit (1);
  }

  if (client.query ("cdevServers", "all",
		    qcallback, 0) != RSVC_SUCCESS) {
    fprintf (stderr, "cannot do query callback\n");
    exit (1);
  }

  if (client.monitorValue ("cdevServers", serverinfo,
			   monitorServerCallback, 0) != RSVC_SUCCESS) {
    fprintf (stderr, "cannot do monitor on server %s %s\n",
	     argv[1], argv[2]);
    exit (1);
  }

  while (1) {
    client.pendIO (5.0);
  }
}
