/*
  hb.c - HeXbombs

  Like bombs, but with hexagons.
*/

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

#include "err.h"
#include "hb.h"

#include <signal.h>
#include <sys/types.h>
#include <sys/time.h>
#include <errno.h>

#include "wind.h"
#include "game.h"

/* ---------- Data structures ---------- */
struct world {
    struct wind *window;
    struct game *game;
};

/* ---------- Globals ---------- */
struct world gworld;
char *whoami = NULL;
char *dpyname = NULL;
Display *dpy = NULL;
int done = 0;
XTextProperty gameTextProp;
char gameName[100];

/* ---------- Function declarations ---------- */
static void init(struct world *, int, char **);
static void do_it(struct world *);
static void term(struct world *);
static void usage(void);

/* ------------------------------------------------------------------------ */
int 
main(int argc, char **argv)
{
  init(&gworld, argc, argv);
  do_it(&gworld);
  term(&gworld);
  return(0);
}

/* ------------------------------------------------------------------------ */
static void
init(struct world *world, int argc, char **argv)
{
    int i;
    struct wind_params wp;

    /* Deal with args */
    whoami = ((whoami = strrchr(argv[0], '/')) ? whoami++ : argv[0]);
    for (i = 1; i < argc; i++) {
	if (argv[i][0] == '-') {
	    switch(argv[i][1]) {
	      case 'd':
		if (!strcmp(&argv[i][1], "display")) {
		    dpyname = argv[++i];
		}
		break;
	      default:
		usage();
		break;
	    }
	}
	else {
	    usage();
	}
    }

    if (!(dpy = XOpenDisplay(dpyname))) {
	do_error(ERR_NODISPLAY, "Can't open display.\n");
    }
    
{
    char hostname[64];
    char *user = (char *) getenv("USER");
    gethostname(hostname, 64);
    sprintf(gameName, "HeXbombs: %s@%s",
	    user ? user : "anonymous",
	    hostname);
    gameTextProp.value = (unsigned char *)gameName;
    gameTextProp.encoding = XA_STRING;
    gameTextProp.format = 8;
    gameTextProp.nitems = strlen(gameName);
}

    wp.win_type = HMINES_WINDOW;
    wp.x = INIT_X;
    wp.y = INIT_Y;
    wp.width = INIT_WIDTH;
    wp.height = INIT_HEIGHT;
    wp.gc = DefaultGC(dpy, DefaultScreen(dpy));

    world->window = wind_create(NULL, &wp);

    world->game = game_create();
}

/* ------------------------------------------------------------------------ */
static void 
do_it(struct world *world)
{
    XEvent xev;

    while (!done) {
	XNextEvent(dpy, &xev);
	do_event(&xev);
    }
}

/* ------------------------------------------------------------------------ */
static void 
term(struct world *world)
{
    game_destroy(world->game);
    wind_destroy(world->window);
    XCloseDisplay(dpy);
}

/* ------------------------------------------------------------------------ */
static void 
usage()
{
    return;
}
