/* Binding for browser using duktape and libdom
 *
 * Copyright 2019 Michael Drake <tlsa@netsurf-browser.org>
 *
 * This file is part of NetSurf, http://www.netsurf-browser.org/
 *
 * Released under the terms of the MIT License,
 *         http://www.opensource.org/licenses/mit-license
 */

init KeyboardEvent (struct dom_keyboard_event *evt::ui_event);

getter KeyboardEvent::key ()
%{
	dom_exception err;
	dom_string *key;

	err = dom_keyboard_event_get_key(priv->parent.parent.evt, &key);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_lstring(ctx, dom_string_data(key), dom_string_length(key));
	dom_string_unref(key);
	return 1;
%}

getter KeyboardEvent::code ()
%{
	dom_exception err;
	dom_string *code;

	err = dom_keyboard_event_get_code(priv->parent.parent.evt, &code);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_lstring(ctx, dom_string_data(code), dom_string_length(code));
	dom_string_unref(code);
	return 1;
%}

getter KeyboardEvent::location ()
%{
	dom_exception err;
	dom_key_location location;

	err = dom_keyboard_event_get_location(priv->parent.parent.evt,
			&location);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_uint(ctx, (duk_uint_t) location);
	return 1;
%}

getter KeyboardEvent::ctrlKey ()
%{
	dom_exception err;
	bool ctrl_key;

	err = dom_keyboard_event_get_ctrl_key(priv->parent.parent.evt,
			&ctrl_key);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_boolean(ctx, (duk_bool_t) ctrl_key);
	return 1;
%}

getter KeyboardEvent::shiftKey ()
%{
	dom_exception err;
	bool shift_key;

	err = dom_keyboard_event_get_shift_key(priv->parent.parent.evt,
			&shift_key);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_boolean(ctx, (duk_bool_t) shift_key);
	return 1;
%}

getter KeyboardEvent::altKey ()
%{
	dom_exception err;
	bool alt_key;

	err = dom_keyboard_event_get_alt_key(priv->parent.parent.evt,
			&alt_key);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_boolean(ctx, (duk_bool_t) alt_key);
	return 1;
%}

getter KeyboardEvent::metaKey ()
%{
	dom_exception err;
	bool meta_key;

	err = dom_keyboard_event_get_meta_key(priv->parent.parent.evt,
			&meta_key);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_boolean(ctx, (duk_bool_t) meta_key);
	return 1;
%}

method KeyboardEvent::getModifierState ()
%{
	dom_string *modifier;
	dom_exception err;
	duk_size_t slen;
	const char *s;
	bool state;

	s = duk_safe_to_lstring(ctx, 0, &slen);
	err = dom_string_create((const uint8_t *)s, slen, &modifier);
	duk_pop(ctx);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	err = dom_keyboard_event_get_modifier_state(priv->parent.parent.evt,
			modifier, &state);
	dom_string_unref(modifier);
	if (err != DOM_NO_ERR) {
		return 0;
	}

	duk_push_boolean(ctx, (duk_bool_t) state);
	return 1;
%}
