#pragma once

#define NODE_ADDON_API_DISABLE_DEPRECATED
#define NAPI_DISABLE_CPP_EXCEPTIONS
#include <napi.h>
#include <cstring>
#include <type_traits>


#ifdef _WIN32
#include <string.h>
inline const char* strcasestr_crossplatform(
	const char *haystack,
	const char *needle
) {
	if (!haystack || !needle) {
		return nullptr;
	}
	if (*needle == '\0') {
		return haystack;
	}

	for (const char *h = haystack; *h != '\0'; ++h) {
		const char *hs = h;
		const char *ns = needle;
		while (*hs != '\0' && *ns != '\0' && _strnicmp(hs, ns, 1) == 0) {
			++hs;
			++ns;
		}
		if (*ns == '\0') {
			return h;
		}
	}

	return nullptr;
}
#else
#include <strings.h>
#define strcasestr_crossplatform strcasestr
#endif


#ifdef _WIN32
#define DBG_EXPORT __declspec(dllexport)
#else
#define DBG_EXPORT
#endif

#define NAPI_ENV Napi::Env env = info.Env();
#define NAPI_HS Napi::HandleScope scope(env);


#define JS_UNDEFINED env.Undefined()
#define JS_NULL env.Null()
#define JS_STR(VAL) Napi::String::New(env, VAL)
#define JS_NUM(VAL) Napi::Number::New(env, static_cast<double>(VAL))
#define JS_EXT(VAL) Napi::External<void>::New(env, static_cast<void*>(VAL))
#define JS_BOOL(VAL) Napi::Boolean::New(env, static_cast<bool>(VAL))
#define JS_OBJECT Napi::Object::New(env)
#define JS_ARRAY Napi::Array::New(env)

#define RET_VALUE(VAL) return VAL;
#define RET_UNDEFINED RET_VALUE(JS_UNDEFINED)
#define RET_NULL RET_VALUE(JS_NULL)
#define RET_STR(VAL) RET_VALUE(JS_STR(VAL))
#define RET_NUM(VAL) RET_VALUE(JS_NUM(VAL))
#define RET_EXT(VAL) RET_VALUE(JS_EXT(VAL))
#define RET_BOOL(VAL) RET_VALUE(JS_BOOL(VAL))


#define JS_THROW(VAL)                                                         \
	Napi::Error::New(env, VAL).ThrowAsJavaScriptException();


#define REQ_ARGS(N)                                                           \
	if (info.Length() < (N)) {                                                \
		JS_THROW("Expected at least " #N " arguments");                       \
		RET_UNDEFINED;                                                        \
	}


#define IS_EMPTY(VAL) (VAL.IsNull() || VAL.IsUndefined())
#define IS_ARG_EMPTY(I) IS_EMPTY(info[I])


#define CHECK_REQ_ARG(I, C, T)                                                \
	if (info.Length() <= (I) || !info[I].C) {                                 \
		JS_THROW("Argument " #I " must be of type `" T "`");                  \
		RET_UNDEFINED;                                                        \
	}

#define CHECK_LET_ARG(I, C, T)                                                \
	if (!(IS_ARG_EMPTY(I) || info[I].C)) {                                    \
		JS_THROW(                                                             \
			"Argument " #I                                                    \
			" must be of type `" T                                            \
			"` or be `null`/`undefined`"                                      \
		);                                                                    \
		RET_UNDEFINED;                                                        \
	}


#define REQ_STR_ARG(I, VAR)                                                   \
	CHECK_REQ_ARG(I, IsString(), "String");                                   \
	std::string VAR = info[I].As<Napi::String>().Utf8Value();

#define USE_STR_ARG(I, VAR, DEF)                                              \
	CHECK_LET_ARG(I, IsString(), "String");                                   \
	std::string VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::String>().Utf8Value();

#define WEAK_STR_ARG(I, VAR)                                                  \
	std::string VAR = info[I].ToString().Utf8Value();

#define LET_STR_ARG(I, VAR) USE_STR_ARG(I, VAR, "")


#define REQ_INT32_ARG(I, VAR)                                                 \
	CHECK_REQ_ARG(I, IsNumber(), "Int32");                                    \
	int32_t VAR = info[I].As<Napi::Number>().Int32Value();

#define USE_INT32_ARG(I, VAR, DEF)                                            \
	CHECK_LET_ARG(I, IsNumber(), "Int32");                                    \
	int32_t VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Number>().Int32Value();

#define WEAK_INT32_ARG(I, VAR)                                                \
	int32_t VAR = info[I].ToNumber().Int32Value();

#define LET_INT32_ARG(I, VAR) USE_INT32_ARG(I, VAR, 0)

#define REQ_INT_ARG(I, VAR) REQ_INT32_ARG(I, VAR)
#define USE_INT_ARG(I, VAR, DEF) USE_INT32_ARG(I, VAR, DEF)
#define WEAK_INT_ARG(I, VAR) WEAK_INT32_ARG(I, VAR)
#define LET_INT_ARG(I, VAR) LET_INT32_ARG(I, VAR)


#define REQ_UINT32_ARG(I, VAR)                                                \
	CHECK_REQ_ARG(I, IsNumber(), "Uint32");                                   \
	uint32_t VAR = info[I].As<Napi::Number>().Uint32Value();

#define USE_UINT32_ARG(I, VAR, DEF)                                           \
	CHECK_LET_ARG(I, IsNumber(), "Uint32");                                   \
	uint32_t VAR = IS_ARG_EMPTY(I)                                            \
		? (DEF)                                                               \
		: info[I].As<Napi::Number>().Uint32Value();

#define WEAK_UINT32_ARG(I, VAR)                                               \
	uint32_t VAR = info[I].ToNumber().Uint32Value();

#define LET_UINT32_ARG(I, VAR) USE_UINT32_ARG(I, VAR, 0)

#define REQ_UINT_ARG(I, VAR) REQ_UINT32_ARG(I, VAR)
#define USE_UINT_ARG(I, VAR, DEF) USE_UINT32_ARG(I, VAR, DEF)
#define WEAK_UINT_ARG(I, VAR) WEAK_UINT32_ARG(I, VAR)
#define LET_UINT_ARG(I, VAR) LET_UINT32_ARG(I, VAR)


#define REQ_INT64_ARG(I, VAR)                                                 \
	CHECK_REQ_ARG(I, IsNumber(), "Int64");                                    \
	int64_t VAR = info[I].As<Napi::Number>().Int64Value();

#define USE_INT64_ARG(I, VAR, DEF)                                            \
	CHECK_LET_ARG(I, IsNumber(), "Int64");                                    \
	int64_t VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Number>().Int64Value();

#define WEAK_INT64_ARG(I, VAR)                                                \
	int64_t VAR = info[I].ToNumber().Int64Value();

#define LET_INT64_ARG(I, VAR) USE_INT64_ARG(I, VAR, 0)


#define REQ_UINT64_ARG(I, VAR)                                                \
	CHECK_REQ_ARG(I, IsNumber(), "Uint64");                                   \
	uint64_t VAR = static_cast<uint64_t>(info[I].As<Napi::Number>().Int64Value());

#define USE_UINT64_ARG(I, VAR, DEF)                                           \
	CHECK_LET_ARG(I, IsNumber(), "Uint64");                                   \
	uint64_t VAR = IS_ARG_EMPTY(I)                                            \
		? (DEF)                                                               \
		: static_cast<uint64_t>(info[I].As<Napi::Number>().Int64Value());

#define WEAK_UINT64_ARG(I, VAR)                                               \
	uint64_t VAR = static_cast<uint64_t>(info[I].ToNumber().Int64Value());

#define LET_UINT64_ARG(I, VAR) USE_UINT64_ARG(I, VAR, 0)


#define REQ_BOOL_ARG(I, VAR)                                                  \
	CHECK_REQ_ARG(I, IsBoolean(), "Bool");                                    \
	bool VAR = info[I].As<Napi::Boolean>().Value();

#define USE_BOOL_ARG(I, VAR, DEF)                                             \
	CHECK_LET_ARG(I, IsBoolean(), "Bool");                                    \
	bool VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Boolean>().Value();

#define WEAK_BOOL_ARG(I, VAR)                                                 \
	bool VAR = info[I].ToBoolean().Value();

#define LET_BOOL_ARG(I, VAR) USE_BOOL_ARG(I, VAR, false)

#define SOFT_BOOL_ARG(I, VAR)                                                 \
	bool VAR = (info.Length() > (I) && info[I].ToBoolean().Value()) || false;


#define REQ_OFFS_ARG(I, VAR)                                                  \
	CHECK_REQ_ARG(I, IsNumber(), "Number");                                   \
	size_t VAR = static_cast<size_t>(info[I].As<Napi::Number>().Int64Value());

#define USE_OFFS_ARG(I, VAR, DEF)                                             \
	CHECK_LET_ARG(I, IsNumber(), "Number");                                   \
	size_t VAR = IS_ARG_EMPTY(I)                                              \
		? (DEF)                                                               \
		: static_cast<size_t>(info[I].As<Napi::Number>().Int64Value());

#define WEAK_OFFS_ARG(I, VAR)                                                 \
	size_t VAR = static_cast<size_t>(info[I].ToNumber().Int64Value());

#define LET_OFFS_ARG(I, VAR) USE_OFFS_ARG(I, VAR, 0)


#define REQ_DOUBLE_ARG(I, VAR)                                                \
	CHECK_REQ_ARG(I, IsNumber(), "Number");                                   \
	double VAR = info[I].As<Napi::Number>().DoubleValue();

#define USE_DOUBLE_ARG(I, VAR, DEF)                                           \
	CHECK_LET_ARG(I, IsNumber(), "Number");                                   \
	double VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Number>().DoubleValue();

#define WEAK_DOUBLE_ARG(I, VAR)                                               \
	double VAR = info[I].ToNumber().DoubleValue();

#define LET_DOUBLE_ARG(I, VAR) USE_DOUBLE_ARG(I, VAR, 0.0)


#define REQ_FLOAT_ARG(I, VAR)                                                 \
	CHECK_REQ_ARG(I, IsNumber(), "Number");                                   \
	float VAR = info[I].As<Napi::Number>().FloatValue();

#define USE_FLOAT_ARG(I, VAR, DEF)                                            \
	CHECK_LET_ARG(I, IsNumber(), "Number");                                   \
	float VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Number>().FloatValue();

#define WEAK_FLOAT_ARG(I, VAR)                                                \
	float VAR = info[I].ToNumber().FloatValue();

#define LET_FLOAT_ARG(I, VAR) USE_FLOAT_ARG(I, VAR, 0.f)


#define REQ_EXT_ARG(I, VAR)                                                   \
	CHECK_REQ_ARG(I, IsExternal(), "Pointer");                                \
	void *VAR = info[I].As< Napi::External<void> >().Data();

#define USE_EXT_ARG(I, VAR, DEF)                                              \
	CHECK_LET_ARG(I, IsExternal(), "Pointer");                                \
	void *VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As< Napi::External<void> >().Data();

#define LET_EXT_ARG(I, VAR) USE_EXT_ARG(I, VAR, nullptr)


#define REQ_FUN_ARG(I, VAR)                                                   \
	CHECK_REQ_ARG(I, IsFunction(), "Function");                               \
	Napi::Function VAR = info[I].As<Napi::Function>();


#define REQ_OBJ_ARG(I, VAR)                                                   \
	CHECK_REQ_ARG(I, IsObject(), "Object");                                   \
	Napi::Object VAR = info[I].As<Napi::Object>();

#define USE_OBJ_ARG(I, VAR, DEF)                                              \
	CHECK_LET_ARG(I, IsObject(), "Object");                                   \
	Napi::Object VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Object>();

#define LET_OBJ_ARG(I, VAR) USE_OBJ_ARG(I, VAR, JS_OBJECT)


#define REQ_ARRV_ARG(I, VAR)                                                  \
	CHECK_REQ_ARG(I, IsArrayBuffer(), "ArrayBuffer");                         \
	Napi::ArrayBuffer VAR = info[I].As<Napi::ArrayBuffer>();


#define REQ_BUF_ARG(I, VAR)                                                   \
	CHECK_REQ_ARG(I, IsBuffer(), "Buffer");                                   \
	Napi::Buffer<uint8_t> VAR = info[I].As< Napi::Buffer<uint8_t> >();


#define REQ_ARRAY_ARG(I, VAR)                                                 \
	CHECK_REQ_ARG(I, IsArray(), "Array");                                     \
	Napi::Array VAR = info[I].As<Napi::Array>();

#define USE_ARRAY_ARG(I, VAR, DEF)                                            \
	CHECK_LET_ARG(I, IsArray(), "Array");                                     \
	Napi::Array VAR = IS_ARG_EMPTY(I) ? (DEF) : info[I].As<Napi::Array>();

#define LET_ARRAY_ARG(I, VAR) USE_ARRAY_ARG(I, VAR, JS_ARRAY)


inline std::vector<std::string> arrayStrToVec(const Napi::Array &arr) {
	uint32_t count = arr.Length();
	std::vector<std::string> result(count);
	for (uint32_t i = 0; i < count; i++) {
		Napi::Value item = arr[i];
		if (item.IsString()) {
			result[i] = item.As<Napi::String>().Utf8Value();
		}
	}
	return result;
}


inline Napi::Array stringsToArray(Napi::Env env, const char **strings, size_t count) {
	Napi::Array arr = JS_ARRAY;
	for (size_t i = 0; i < count; i++) {
		arr.Set(i, strings[i]);
	}
	return arr;
}


inline Napi::Array vecStrToArray(Napi::Env env, const std::vector<std::string> &strings) {
	Napi::Array arr = JS_ARRAY;
	size_t count = strings.size();
	for (size_t i = 0; i < count; i++) {
		arr.Set(i, strings[i]);
	}
	return arr;
}


#define LET_ARRAY_STR_ARG(I, VAR)                                             \
	USE_ARRAY_ARG(I, __ARRAY_ ## VAR, JS_ARRAY);                 \
	std::vector<std::string> VAR = arrayStrToVec(__ARRAY_ ## VAR);


#define RET_ARRAY_STR(VAL) RET_VALUE(vecStrToArray(env, VAL))


#define REQ_TYPED_ARRAY_ARG(I, VAR)                                           \
	CHECK_REQ_ARG(I, IsTypedArray(), "TypedArray");                           \
	Napi::TypedArray VAR = info[I].As<Napi::TypedArray>();


#define DES_CHECK                                                             \
	if (_isDestroyed) return;

#define THIS_CHECK                                                            \
	NAPI_ENV;                                                                 \
	if (_isDestroyed) RET_UNDEFINED;

#define CACHE_CAS(CACHE, V)                                                   \
	if (CACHE == V) {                                                         \
		RET_UNDEFINED;                                                        \
	}                                                                         \
	CACHE = V;

#define SETTER_CHECK(C, T)                                                    \
	if (!value.C) {                                                           \
		JS_THROW("Value must be " T);                                         \
		RET_UNDEFINED;                                                        \
	}


#define JS_METHOD(NAME) Napi::Value NAME(const Napi::CallbackInfo &info)

#define ACCESSOR_RW(CLASS, NAME)                                              \
	InstanceAccessor(#NAME, &CLASS::NAME ## Getter, &CLASS::NAME ## Setter)

#define ACCESSOR_R(CLASS, NAME)                                               \
	InstanceAccessor(#NAME, &CLASS::NAME ## Getter, nullptr)

#define ACCESSOR_M(CLASS, NAME)                                               \
	InstanceMethod(#NAME, &CLASS::NAME)

#define THIS_OBJ(VAR)                                                         \
	Napi::Object VAR = info.This().As<Napi::Object>();

#define SETTER_STR_ARG                                                        \
	SETTER_CHECK(IsString(), "String");                                       \
	std::string v = value.As<Napi::String>().Utf8Value();

#define SETTER_INT32_ARG                                                      \
	SETTER_CHECK(IsNumber(), "Int32");                                        \
	int32_t v = value.As<Napi::Number>().Int32Value();

#define SETTER_INT_ARG SETTER_INT32_ARG

#define SETTER_BOOL_ARG                                                       \
	SETTER_CHECK(IsBoolean(), "Bool");                                        \
	bool v = value.As<Napi::Boolean>().Value();

#define SETTER_UINT32_ARG                                                     \
	SETTER_CHECK(IsNumber(), "Uint32");                                       \
	uint32_t v = value.As<Napi::Number>().Uint32Value();

#define SETTER_UINT_ARG SETTER_UINT32_ARG

#define SETTER_INT64_ARG                                                      \
	SETTER_CHECK(IsNumber(), "Int64");                                        \
	int64_t v = value.As<Napi::Number>().Int64Value();

#define SETTER_UINT64_ARG                                                     \
	SETTER_CHECK(IsNumber(), "Uint64");                                       \
	uint64_t v = static_cast<uint64_t>(value.As<Napi::Number>().Int64Value());

#define SETTER_OFFS_ARG                                                       \
	SETTER_CHECK(IsNumber(), "Number");                                       \
	size_t v = static_cast<size_t>(value.As<Napi::Number>().Int64Value());

#define SETTER_DOUBLE_ARG                                                     \
	SETTER_CHECK(IsNumber(), "Number");                                       \
	double v = value.As<Napi::Number>().DoubleValue();

#define SETTER_FLOAT_ARG                                                      \
	SETTER_CHECK(IsNumber(), "Number");                                       \
	float v = value.As<Napi::Number>().FloatValue();

#define SETTER_EXT_ARG                                                        \
	SETTER_CHECK(IsExternal(), "Pointer");                                    \
	void *v = value.As< Napi::External<void> >().Data();

#define SETTER_FUN_ARG                                                        \
	SETTER_CHECK(IsFunction(), "Function");                                   \
	Napi::Function v = value.As<Napi::Function>()

#define SETTER_OBJ_ARG                                                        \
	SETTER_CHECK(IsObject(), "Object");                                       \
	Napi::Object v = value.As<Napi::Object>()

#define SETTER_ARRV_ARG                                                       \
	SETTER_CHECK(IsArrayBuffer(), "TypedArray");                              \
	Napi::ArrayBuffer v = value.As<Napi::ArrayBuffer>();


#define GET_AND_THROW_LAST_ERROR()                                            \
	do {                                                                      \
		const napi_extended_error_info *error_info;                           \
		napi_get_last_error_info((env), &error_info);                         \
		bool is_pending;                                                      \
		napi_is_exception_pending((env), &is_pending);                        \
		/* If an exception is already pending, don't rethrow it */            \
		if (!is_pending) {                                                    \
			const char* error_message = error_info->error_message != NULL     \
				? error_info->error_message                                   \
				: "empty error message";                                      \
			JS_THROW(error_message);                                          \
		}                                                                     \
	} while (0)

#define NAPI_CALL(the_call)                                                   \
	do {                                                                      \
		if ((the_call) != napi_ok) {                                          \
			GET_AND_THROW_LAST_ERROR();                                       \
			RET_UNDEFINED;                                                    \
		}                                                                     \
	} while (0)

#define JS_RUN(code, VAR)                                                     \
	napi_value __RESULT_ ## VAR;                                              \
	NAPI_CALL(                                                                \
		napi_run_script(env, napi_value(JS_STR(code)), &__RESULT_ ## VAR)     \
	);                                                                        \
	Napi::Value VAR(env, __RESULT_ ## VAR);


template<typename Type = const uint8_t>
inline Type* getArrayData(
	Napi::Env env,
	Napi::Object obj,
	int32_t *num = nullptr
) {
	using ValueType = std::remove_cv_t<Type>;
	using ByteType = std::conditional_t<std::is_const_v<Type>, const uint8_t, uint8_t>;

	Type *out = nullptr;
	if (num) {
		*num = 0;
	}

	if (obj.IsTypedArray()) {
		Napi::TypedArray ta = obj.As<Napi::TypedArray>();
		size_t offset = ta.ByteOffset();
		size_t byteLength = ta.ByteLength();
		Napi::ArrayBuffer arr = ta.ArrayBuffer();
		if (byteLength > 0 && byteLength < sizeof(ValueType)) {
			JS_THROW("Array data does not contain a complete item of the requested type.");
			return nullptr;
		}
		if ((byteLength % sizeof(ValueType)) != 0) {
			JS_THROW("Array byte length must be a multiple of the requested type size.");
			return nullptr;
		}
		ByteType *base = reinterpret_cast<ByteType *>(arr.Data());
		ByteType *raw = base == nullptr ? nullptr : base + offset;
		if (
			raw != nullptr &&
			(reinterpret_cast<uintptr_t>(raw) % alignof(ValueType)) != 0
		) {
			JS_THROW("Array data is not properly aligned for the requested type.");
			return nullptr;
		}
		if (num) {
			*num = static_cast<int32_t>(byteLength / sizeof(ValueType));
		}
		out = reinterpret_cast<Type *>(raw);
	} else if (obj.IsArrayBuffer()) {
		Napi::ArrayBuffer arr = obj.As<Napi::ArrayBuffer>();
		size_t byteLength = arr.ByteLength();
		if (byteLength > 0 && byteLength < sizeof(ValueType)) {
			JS_THROW("Array data does not contain a complete item of the requested type.");
			return nullptr;
		}
		if ((byteLength % sizeof(ValueType)) != 0) {
			JS_THROW("Array byte length must be a multiple of the requested type size.");
			return nullptr;
		}
		ByteType *raw = reinterpret_cast<ByteType *>(arr.Data());
		if (
			raw != nullptr &&
			(reinterpret_cast<uintptr_t>(raw) % alignof(ValueType)) != 0
		) {
			JS_THROW("Array data is not properly aligned for the requested type.");
			return nullptr;
		}
		if (num) {
			*num = static_cast<int32_t>(byteLength / sizeof(ValueType));
		}
		out = reinterpret_cast<Type *>(raw);
	} else {
		JS_THROW("Argument must be of type `TypedArray`.");
	}

	return out;
}


template<typename Type = const uint8_t>
inline Type* getBufferData(
	Napi::Env env,
	Napi::Object obj,
	int32_t *num = nullptr
) {
	using ValueType = std::remove_cv_t<Type>;
	using ByteType = std::conditional_t<std::is_const_v<Type>, const uint8_t, uint8_t>;

	if (num) {
		*num = 0;
	}

	if (!obj.IsBuffer()) {
		JS_THROW("Argument must be of type `Buffer`.");
		return nullptr;
	}

	Napi::Buffer<uint8_t> arr = obj.As< Napi::Buffer<uint8_t> >();
	size_t byteLength = arr.Length();
	if (byteLength > 0 && byteLength < sizeof(ValueType)) {
		JS_THROW("Buffer does not contain a complete item of the requested type.");
		return nullptr;
	}
	if ((byteLength % sizeof(ValueType)) != 0) {
		JS_THROW("Buffer byte length must be a multiple of the requested type size.");
		return nullptr;
	}
	ByteType *raw = reinterpret_cast<ByteType *>(arr.Data());
	if (
		raw != nullptr &&
		(reinterpret_cast<uintptr_t>(raw) % alignof(ValueType)) != 0
	) {
		JS_THROW("Buffer data is not properly aligned for the requested type.");
		return nullptr;
	}
	if (num) {
		*num = static_cast<int32_t>(byteLength / sizeof(ValueType));
	}
	return reinterpret_cast<Type*>(raw);
}


template<typename Type = const uint8_t>
inline Type *getData(
	Napi::Env env,
	Napi::Object obj,
	int32_t *num = nullptr
) {
	Type *out = nullptr;
	if (num) {
		*num = 0;
	}

	if (obj.IsTypedArray() || obj.IsArrayBuffer()) {
		out = getArrayData<Type>(env, obj, num);
	} else if (obj.IsBuffer()) {
		out = getBufferData<Type>(env, obj, num);
	} else {
		bool hasData = false;
		napi_status hasStatus = napi_has_named_property(
			env, obj, "data", &hasData
		);
		if (hasStatus != napi_ok) {
			if (env.IsExceptionPending()) {
				env.GetAndClearPendingException();
			}
			return nullptr;
		}
		if (!hasData) {
			return nullptr;
		}

		napi_value rawData;
		napi_status getStatus = napi_get_named_property(
			env, obj, "data", &rawData
		);
		if (getStatus != napi_ok) {
			if (env.IsExceptionPending()) {
				env.GetAndClearPendingException();
			}
			return nullptr;
		}

		Napi::Value dataValue(env, rawData);
		if (
			dataValue.IsTypedArray() ||
			dataValue.IsArrayBuffer() ||
			dataValue.IsBuffer()
		) {
			Napi::Object data = dataValue.As<Napi::Object>();
			if (data.IsTypedArray() || data.IsArrayBuffer()) {
				out = getArrayData<Type>(env, data, num);
			} else if (data.IsBuffer()) {
				out = getBufferData<Type>(env, data, num);
			}
		}
	}

	return out;
}


inline Napi::Value consoleLog(
	Napi::Env env,
	int32_t argc,
	const Napi::Value *argv
) {
	JS_RUN("console.log", log);
	std::vector<napi_value> args;
	for (int32_t i = 0; i < argc; i++) {
		args.push_back(napi_value(argv[i]));
	}
	log.As<Napi::Function>().Call(args);
	RET_UNDEFINED;
}


inline Napi::Value consoleLog(Napi::Env env, const std::string &message) {
	Napi::Value arg = JS_STR(message);
	consoleLog(env, 1, &arg);
	RET_UNDEFINED;
}

inline Napi::Value globalLog(
	Napi::Env env,
	const std::string &name,
	const std::string &level,
	int32_t argc,
	const Napi::Value *argv
) {
	JS_RUN("global.AddonTools.log", log);
	std::vector<napi_value> args;
	args.push_back(napi_value(JS_STR(name)));
	args.push_back(napi_value(JS_STR(level)));
	for (int32_t i = 0; i < argc; i++) {
		args.push_back(napi_value(argv[i]));
	}
	log.As<Napi::Function>().Call(args);
	RET_UNDEFINED;
}


inline Napi::Value globalLog(
	Napi::Env env,
	const std::string &name,
	const std::string &level,
	const std::string &message
) {
	Napi::Value arg = JS_STR(message);
	globalLog(env, name, level, 1, &arg);
	RET_UNDEFINED;
}


inline void eventEmit(
	Napi::Object that,
	const std::string &name,
	int32_t argc = 0,
	const Napi::Value *argv = nullptr,
	napi_async_context context = nullptr
) {
	if (!that.Has("emit")) {
		return;
	}

	Napi::Env env = that.Env();

	Napi::String eventName = JS_STR(name);
	Napi::Function thatEmit = that.Get("emit").As<Napi::Function>();

	std::vector<napi_value> args;
	args.push_back(napi_value(eventName));
	for (int32_t i = 0; i < argc; i++) {
		args.push_back(napi_value(argv[i]));
	}

	if (context) {
		thatEmit.MakeCallback(that, args, context);
	} else {
		thatEmit.Call(that, args);
	}
}


typedef Napi::Value (*Es5MethodCallback)(const Napi::CallbackInfo& info);
typedef Napi::Value (*Es5GetterCallback)(const Napi::CallbackInfo& info);
typedef void (*Es5SetterCallback)(const Napi::CallbackInfo& info);


#define DECLARE_ES5_CLASS(CLASS, NAME)                                        \
public:                                                                       \
	inline static CLASS *unwrap(Napi::Object thatObj) {                       \
		CLASS *that = nullptr;                                                \
		napi_status ns = napi_unwrap(                                         \
			thatObj.Env(),                                                    \
			thatObj.Get(_nameEs5),                                            \
			reinterpret_cast<void**>(&that)                                   \
		);                                                                    \
		if (ns != napi_ok) {                                                  \
			return nullptr;                                                   \
		}                                                                     \
		return that;                                                          \
	}                                                                         \
private:                                                                      \
	inline static CLASS *unwrapChecked(                                       \
		const Napi::CallbackInfo &info                                        \
	) {                                                                       \
		CLASS *that = unwrap(info.This().As<Napi::Object>());                 \
		if (that == nullptr) {                                                \
			Napi::TypeError::New(                                             \
				info.Env(),                                                   \
				"Invalid `this` for `" #CLASS "`"                             \
			).ThrowAsJavaScriptException();                                   \
		}                                                                     \
		return that;                                                          \
	}                                                                         \
	static Napi::FunctionReference _ctorEs5;                                  \
	static const char *_nameEs5;                                              \
	static void _finalizeEs5(napi_env e, void *dest, void* hint);             \
	static napi_value _createEs5(napi_env e, napi_callback_info i);           \
	inline void super(                                                        \
		const Napi::CallbackInfo& info,                                       \
		int32_t argc,                                                         \
		const Napi::Value *argv                                               \
	) {                                                                       \
		Napi::Function ctor = _ctorEs5.Value();                               \
		if (ctor.Has("super_")) {                                             \
			Napi::Function _super = ctor.Get("super_").As<Napi::Function>();  \
			std::vector<napi_value> args;                                     \
			for (int32_t i = 0; i < argc; i++) {                              \
				args.push_back(argv[i]);                                      \
			}                                                                 \
			_super.Call(info.This(), args);                                   \
		}                                                                     \
	}                                                                         \
	inline void super(                                                        \
		const Napi::CallbackInfo& info,                                       \
		int32_t argc = 0,                                                     \
		const napi_value *argv = nullptr                                      \
	) {                                                                       \
		Napi::Function ctor = _ctorEs5.Value();                               \
		if (ctor.Has("super_")) {                                             \
			Napi::Function _super = ctor.Get("super_").As<Napi::Function>();  \
			_super.Call(info.This(), argc, argv);                             \
		}                                                                     \
	}                                                                         \
	inline static Napi::Function wrap(Napi::Env env) {                        \
		napi_value __initResult;                                              \
		napi_create_function(                                                 \
			env, #NAME, 0, _createEs5, nullptr, &__initResult                 \
		);                                                                    \
		Napi::Function ctor = Napi::Function(env, __initResult);              \
		_ctorEs5 = Napi::Persistent(ctor);                                    \
		_ctorEs5.SuppressDestruct();                                          \
		return ctor;                                                          \
	}                                                                         \
	inline static void method(                                                \
		const char *name,                                                     \
		Es5MethodCallback cb                                                  \
	) {                                                                       \
		Napi::Object proto = (                                                \
			_ctorEs5.Value().Get("prototype").As<Napi::Object>()              \
		);                                                                    \
		proto.DefineProperty(                                                 \
			Napi::PropertyDescriptor::Function(                               \
				proto.Env(), proto, name, cb                                  \
			)                                                                 \
		);                                                                    \
	}                                                                         \
	inline static void accessorR(                                             \
		const char *name,                                                     \
		Es5GetterCallback getter                                              \
	) {                                                                       \
		Napi::Object proto = (                                                \
			_ctorEs5.Value().Get("prototype").As<Napi::Object>()              \
		);                                                                    \
		proto.DefineProperty(                                                 \
			Napi::PropertyDescriptor::Accessor(                               \
				proto.Env(), proto, name, getter                              \
			)                                                                 \
		);                                                                    \
	}                                                                         \
	inline static void accessorRw(                                            \
		const char *name,                                                     \
		Es5GetterCallback getter,                                             \
		Es5SetterCallback setter                                              \
	) {                                                                       \
		Napi::Object proto = (                                                \
			_ctorEs5.Value().Get("prototype").As<Napi::Object>()              \
		);                                                                    \
		proto.DefineProperty(                                                 \
			Napi::PropertyDescriptor::Accessor(                               \
				proto.Env(),                                                  \
				proto,                                                        \
				name,                                                         \
				getter,                                                       \
				setter                                                        \
			)                                                                 \
		);                                                                    \
	}


#define JS_DECLARE_METHOD(CLASS, NAME)                                        \
	inline static JS_METHOD(__st_##NAME) {                                    \
		CLASS *that = CLASS::unwrapChecked(info);                             \
		if (that == nullptr) {                                                \
			return info.Env().Undefined();                                    \
		}                                                                     \
		return that->__i_##NAME(info);                                        \
	};                                                                        \
	JS_METHOD(__i_##NAME);

#define JS_DECLARE_GETTER(CLASS, NAME) JS_DECLARE_METHOD(CLASS, NAME##Getter)

#define JS_DECLARE_SETTER(CLASS, NAME)                                        \
	inline static void __st_##NAME##Setter(                                   \
		const Napi::CallbackInfo &info                                        \
	) {                                                                       \
		CLASS *that = CLASS::unwrapChecked(info);                             \
		if (that == nullptr) {                                                \
			return;                                                           \
		}                                                                     \
		that->__i_##NAME##Setter(info, info[0]);                              \
	}                                                                         \
	Napi::Value __i_##NAME##Setter(                                           \
		const Napi::CallbackInfo &info,                                       \
		const Napi::Value &value                                              \
	);

#define JS_IMPLEMENT_METHOD(CLASS, NAME)                                      \
	JS_METHOD(CLASS::__i_##NAME)

#define JS_IMPLEMENT_GETTER(CLASS, NAME)                                      \
	JS_IMPLEMENT_METHOD(CLASS, NAME##Getter)

#define JS_IMPLEMENT_SETTER(CLASS, NAME)                                      \
	Napi::Value CLASS::__i_##NAME##Setter(                                    \
		const Napi::CallbackInfo &info,                                       \
		const Napi::Value &value                                              \
	)

#define JS_ASSIGN_METHOD(NAME) method(#NAME, __st_##NAME)
#define JS_ASSIGN_GETTER(NAME) accessorR(#NAME, __st_##NAME##Getter)
#define JS_ASSIGN_SETTER(NAME)                                                \
	accessorRw(#NAME, __st_##NAME##Getter, __st_##NAME##Setter)

#define IMPLEMENT_ES5_CLASS(CLASS)                                            \
	Napi::FunctionReference CLASS::_ctorEs5;                                  \
	const char *CLASS::_nameEs5 = #CLASS;                                     \
	void CLASS::_finalizeEs5(napi_env e, void *dest, void* hint) {            \
		CLASS *instance = reinterpret_cast<CLASS*>(dest);                     \
		delete instance;                                                      \
	}                                                                         \
	napi_value CLASS::_createEs5(napi_env env, napi_callback_info i) {        \
		Napi::CallbackInfo info(env, i);                                      \
		CLASS *instance = new CLASS(info);                                    \
		Napi::Object wrapObj = JS_OBJECT;                                     \
		info.This().As<Napi::Object>().Set(_nameEs5, wrapObj);                \
		napi_wrap(env, wrapObj, instance, _finalizeEs5, nullptr, nullptr);    \
		return info.Env().Undefined();                                        \
	}
