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

bool dflag = false;

void usage(void) {
  fprintf(stderr, "Usage: indextest <file>\n");

}


bool getkey(const char * prompt, uint32 & key) {
  char line[256];
  char * cp;

  fprintf(stdout, prompt); fflush(stdout);
  
  fgets(line, sizeof(line), stdin);
  line[sizeof(line)-1] = 0;
  if (strlen(line) == 0) return false;
  if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
  if (strlen(line) == 0) return false;
  key = 0;
  
  for (cp = line; *cp != 0; cp++) {
    if ((*cp >= '0') && (*cp <= '9')) key = key * 10 + (*cp - '0');
    else return false;
  };
  return true;

}

bool process_flags(char * f) {
  int i;


  if (f == NULL) {
    usage();
    return false;
  };
  if (f[0] != '-') {
    usage();
    return false;
  };
  i=1;
  while (f[i]) {
    if (f[i] == 'd') dflag = true;
    else {
      usage();
      return false;
    };
    i++;  
  };  
  return true;
}

int main(int argc, char * argv[]) {
  slindex_t idx("Test");
  uint32 status;
  char * filename;
  uint32 primary_key;
  uint32 secondary_key;

  if (argc < 2) {
    usage();
    return EXIT_FAILURE;
  };
  filename = argv[argc-1];
  if (argc > 2) if (!process_flags(argv[1])) return EXIT_FAILURE;
  if (argc > 3) if (!process_flags(argv[2])) return EXIT_FAILURE;
  if (argc > 4) {
    usage();
    return EXIT_FAILURE;
  };  

  idx.set_file(filename);
  idx.define_index(4,
                   "NOFILE.NO",
                   dflag);


  status = idx.open();

  if (status) {
    fprintf(stderr, "index::open() returned %lu\n", status);
    return EXIT_FAILURE;
  };
  
  while (getkey("Primary key: ", primary_key)) {
    while (!getkey("Secondary key: ", secondary_key));
    status = idx.insert((unsigned char *)&primary_key, secondary_key);
    if (status) {
      fprintf(stderr, 
              "Error %lu inserting {%lu, %lu} into index\n",
              status,
              primary_key,
              secondary_key);
    };
  };

  fprintf(stdout, "Index complete\n");

  
  
  while (getkey("Lookup key: ", primary_key)) {
    status = idx.lookup((unsigned char *)&primary_key, secondary_key);
    if (status == 0) {
      fprintf(stdout, "%lu mapped to %lu\n", primary_key, secondary_key);
    } else {
      fprintf(stdout, "Error %lu looking up %lu\n", status, primary_key);
    };
  };
  
  
  return EXIT_SUCCESS;
   

}