/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

%{
#include <haka/log.h>
#include <wchar.h>
#include <stdlib.h>

static wchar_t* str2wstr(const char *str, int len)
{
	wchar_t *p;
	if (str == 0 || len < 0) {
		return 0;
	}

	p = (wchar_t *)malloc((len+1)*sizeof(wchar_t));
	if (p == 0) {
		return 0;
	}

	if (mbstowcs(p, str, len) == -1) {
		free(p);
		return 0;
	}

	p[len] = 0;
	return p;
}
%}

%typemap(in, checkfn="SWIG_lua_isnilstring", fragment="SWIG_lua_isnilstring") wchar_t *
%{
	{
		const char *str = lua_tostring(L, $input);
		int len = lua_objlen(L, $input);

		if (!str && len == 0) {
			 $1 = NULL;
		} else {
			$1 = str2wstr(str, len);
			if ($1 == 0) {
				lua_pushfstring(L, "Error in converting to wchar (arg %d)", $input);
				SWIG_fail;
			}
		}
	}
%}

%typemap(freearg) wchar_t *
%{
	free($1);
%}

%typemap(memberin) wchar_t *
%{
	free($1);
	$1 = $input;
	$input = NULL;
%}

%typemap(typecheck) wchar_t * = char *;
