//  SWM - "Superior, small, symphatetic, smart & state of the art Window Manager"
//  simply SWM

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
#include <sys/time.h>
#include <X11/Xlib.h>
#include <X11/Xproto.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <locale.h>
#include <X11/Xlocale.h>

#include "main.hh"

//********************************************************************

Display *dpy;
unsigned long screen;
Window root;

//********************************************************************

int
main (int argc, char **argv)
{
	g_argc = argc;
	g_argv = argv;

	setlocale (LC_ALL, "");
	home_dir = getenv ("HOME");

	// parse command line
	for (int i = 1; i < argc; i++)
	{
		if (strncasecmp (argv[i], "-v", 2) == 0 || strncasecmp (argv[i], "--version", 9) == 0) {
			fprintf (stderr, "SWM ver. %s\n", VERSION);
			return 0;
		}
	};

	// connect to X server
	dpy = XOpenDisplay (dpy_name);
	int i = XConnectionNumber (dpy);
	if (fcntl (i, F_SETFD, 1) == -1)
	{
		fprintf (stderr, "swm fatal: close-on-exec failed\n");
		exit (1);
	};
	 
	screen = DefaultScreen (dpy);
	int disp_wd = DisplayWidth (dpy, screen);
	int disp_ht = DisplayHeight (dpy, screen);
	
	root = RootWindow (dpy, screen);
	if (!root) {
		fprintf (stderr, "swm fatal: screen %ld is not a valid screen\n", screen);
		exit (1);
	};

	if (XSetLocaleModifiers ("") == NULL)
		fprintf (stderr, "swm warning: X server doesn't support locale\n");
	
	
	
	XSetWindowAttributes at;
	unsigned long vm;
	XGCValues gcv;
	unsigned long gcm;
	Junk junk;
	
	at.cursor = cursor;
	at.event_mask =
		ButtonPressMask | ButtonReleaseMask | PointerMotionMask
		| ExposureMask | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;

	vm = CWBorderPixel | CWEventMask | CWSaveUnder;
	w = XCreateWindow
		(dpy, root, 100, 100, disp_wd/2, disp_ht/2, 2,
		 CopyFromParent, InputOutput, CopyFromParent, vm, &at);

	XEvent x;

	// handle events
	while (!done) {
		XNextEvent (dpy, &x);
		switch (x.type)
		{
		case KeyPress:
			keysym = XLookupKeysym (&x.xkey, 0);
			switch (keysym) {
				case XK_Up:	dy = -step; event->handled = 1; break;
				case XK_q:	done = 1;
			}
			printf ("'%s' %s \n", XKeysymToString(keysym), x.type==KeyPress?"press":"release");
			break;
		case ButtonPress:		break;
		}
	}

}

