// simple program to demonstrate how a cdev server uses rsvc library
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <rsvcClient.h>
#include <rsvcUdpClient.h>

static void rsvcCallback (int status, void* /* arg */, rsvcData* /* data */)
{
  if (status == RSVC_SUCCESS) {
    printf ("register server success\n");
  }
  else
    printf ("register server failed\n");
}


int main (int argc, char** argv)
{
  rsvcData serverinfo;
  rsvcData udpinfo;

  if (argc < 4) {
    fprintf (stderr, "Usage: %s name domain serverhost serverport\n", argv[0]);
    exit (1);
  }
  char hostname[256];
  gethostname (hostname, sizeof (hostname));
  struct timeval tv;
  gettimeofday (&tv, 0);
  
  serverinfo.insert ("name", argv[1]);
  serverinfo.insert ("domain", argv[2]);
  serverinfo.insert ("host", hostname);
  serverinfo.insert ("owner", "chen");
  serverinfo.insert ("time", (long)tv.tv_sec);
  serverinfo.insert ("port", (long)tv.tv_sec%10000);
  serverinfo.insert ("pid", getpid ());

  udpinfo.insert ("name", argv[1]);
  udpinfo.insert ("domain", argv[2]);

  rsvcClient client;
  rsvcUdpClient udpclient;

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

  if (udpclient.connect (argv[3], atoi (argv[4]) + 1024) != RSVC_SUCCESS) {
    fprintf (stderr, "Cannot connect to udp port\n");
    exit (1);
  }

  // register server information
  if (client.insertValue ("cdevServers", serverinfo, rsvcCallback, 0, 1) !=
      RSVC_SUCCESS) {
    fprintf (stderr, "Cannot send server information to rsvc\n");
    client.disconnect ();
    udpclient.disconnect ();
    exit (1);
  }
  
  int st = 0;
  while (1) {
    if ((st = client.pendIO (5.0)) != RSVC_SUCCESS && st != RSVC_TIMEOUT)
      break;
    if (udpclient.update (udpinfo) != RSVC_SUCCESS)
      printf ("udp update failed\n");
  }
}

    
