/* System includes */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

/* libhomeradar header include */
#include "libhomeradar.h"

/* Global variable to libhomeradar */
LHR H = NULL;

/* Callback function to show aircraft informations */
void newcontact(void *handle,const int *id, LHR_CONTACT *C) {

  /* Show only ICAO24 and registration */
  printf("%sContact: %s [%s]\n",(C->newcontact)?"AIR":"",
          C->icao24,(C->reg)?C->reg:"UNKNOWN");

  /* Free LHR_CONTACT struct */
  homeradar_freecontact(C);
}

/* Shutdown library and finish program */
void shutdownlib(int sig) {

  printf("Shutdown system. Closing library handle...\n");

  /* Close lib handle */
  if (H) homeradar_destroy(H);
  exit(0);
}

/* Main program */
int main(int argc, char **argv) {
  int e;

  /* Init global variable */
  H = homeradar_init(16,LHR_AUTOCONNECT|LHR_LOOKUP_REG,&e,NULL);

  /* No error */
  if (H == NULL) {
    printf("Error initializing libhomeradar. Errorcode #%d\n",e);
    return 255;
  }

  /* Catch SIGINT signals (CTRL-C) */
  (void)signal(SIGINT, shutdownlib);

  /* Load databases from disc
     Files should be located within the current directory */
  homeradar_load_databases(H, "./");

  /* Add host without event listener */
  e = homeradar_addhost(H, "sbs1.libhomeradar.org", 33033, LHR_SBS1, 0, NULL);

  /* Show only aircrafts which are registered in the Russian Federation */
  (void)homeradar_addfilter(H, LHR_FILTER_BYICAO24|LHR_FILTER_INCLUDE, "100000~1FFFFF", e);

  /* Setup the event listener for the LHR_ONCONTACT event */
  if (homeradar_onhandler(H, LHR_ONCONTACT, e, newcontact)==0) {
    printf("Unable to add event listener\n");
  }

  /* Do nothing */
  while (1) usleep(300000);

  /* Destroy lib handler */
  homeradar_destroy(H);

  /* Return success */
  return 0;
}
