
#include <assert.h>
#include "Xlib.h"

namespace sp { namespace Xlib {

namespace _priv {
	// Define a global display (for simplicity, we always connect to local one.)
	::Display* display = NULL;
};

void init()
{
	_priv::display = XOpenDisplay(NULL);
}

void shutdown()
{
	assert(_priv::display != NULL);
	XCloseDisplay(_priv::display);
	_priv::display = NULL;
}

::Display* getDisplay()
{
	assert(_priv::display != NULL);
	return _priv::display;
}

// Implementation borrowed from SFML :)
::Window getParentWindow(::Window win)
{
	::Window     root, parent;
	::Window*    children = nullptr;
	unsigned int numChildren;

	::XQueryTree(getDisplay(), win, &root, &parent, &children, &numChildren);

	// Children information is not used, so must be freed.
	if (children != nullptr)
		XFree(children);

	return parent;
}

::Atom getAtom(const std::string& name, bool onlyIfExists)
{
	return XInternAtom(getDisplay(), name.c_str(), onlyIfExists);
}

} } // namespace sp::Xlib
