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


void check_env(void) {
  char * lang;
  char * nlspath;

  if ((lang = getenv("LC_MESSAGES")) != NULL) {
    fprintf(stdout, "Translating messages using locale specified in LC_MESSAGES\n");
  } else if ((lang = getenv("LANG")) != NULL) {
    fprintf(stdout, "Translating messages using local specified in LANG\n");
  } else {
    fprintf(stdout, "No message locale set; using \"en_US.ISO8859-1\"\n");
    lang = "en_US.ISO8859-1";
  };

  if ((nlspath = getenv("NLSPATH")) != NULL) {
    fprintf(stdout, "NLSPATH is set\n");
  } else {
    fprintf(stdout, "NLSPATH not set; will attempt to find catalog using PATH\n");
  };

}


void translate(const char * msg) {
  const char * p = msg;
  uint32 status;
  int argc;
  uint32 res;
  utf8String errorText = NULL;

  while ((*p == ' ') || (*p == '\t')) p++;
  if (*p == 0) {
    fprintf(stderr, "\"%s\" is not a valid status code\n", msg);
    return;
  };

  if (*p == '0') {
    if ((*(p+1) == 'x') || (*(p+1) == 'X')) {
      argc = sscanf(p+2, "%lx", &status);
    } else {
      argc = sscanf(p+1, "%lo", &status);
    };
  } else {
    argc = sscanf(p, "%lu", &status);
  };

  if (argc != 1) {
    fprintf(stderr, "\"%s\" is not a valid status code\n", msg);
    return;
  };
  

  res = JNH_get_error(status,
                      &errorText);

  fprintf(stdout, "%s\n", errorText);

  JNH_release_utf8String(errorText);

}

int main(int argc, char * argv[]) {
  bool interactive = false;
  char line[512];

  interactive = (argc <= 1);

  if (argc > 2) {
    fprintf(stderr, "usage: jmsg [ <error-code> ]\n");
    return EXIT_FAILURE;
  };

  check_env();

  if (!interactive) {
    translate(argv[1]);
  } else {
    while (true) {
      fprintf(stdout, "Code: ");
      fflush(stdout);
      fgets(line, sizeof(line), stdin);
      line[sizeof(line)-1] = 0;
      if (line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0;
      if (strlen(line) == 0) break;
      translate(line);
    }; 
  };

  return EXIT_SUCCESS;  
}