const tcc = require('./index');
const StructType = require('ref-struct');
const ref = require('ref');
const wchar_t = require('ref-wchar');

let state = tcc.DefaultTcc();
let gen = tcc.CodeGenerator();

gen.loadBasicTypes();
gen.addTopDeclaration(tcc.Declaration('#include <stdio.h>\n#include <locale.h>'));

function escape_wchar(s) {
    const Iconv = require('iconv').Iconv;
    return [...new Uint32Array(
        new Uint8Array(
            (new Iconv('UTF-8', 'WCHAR_T')).convert(s)
        ).buffer)].map(
        (el) => '\\x' + el.toString(16)
    ).join('');
}

let show = tcc.c_function('WCString', 'show', [['string', 's'], ['wstring', 'ws']],
    `
    setlocale(LC_ALL, "");
    //static wchar_t AL[] = L"1\\xe4\\x20ac" L"423456789";
    static wchar_t AL2[] = L"${escape_wchar('ö€äü')}";

    printf("CString: %s\\n", s);
    printf("WCString: %ls\\n", ws);

    return AL2;
    `
);
gen.addDeclaration(show);
console.log(gen.codeWithLineNumbers());

/*
// sync compilation
state.compile(gen.code());
console.log(state.relocate());
gen.bindState(state);

function CString(s, encoding) {
    let buf = new Buffer(s + '\0', encoding);
    buf.type = ref.types.CString;
    return buf;
}

function WCString(s, encoding) {
    const Iconv = require('iconv').Iconv;
    let setter = new Iconv(encoding || 'UTF-8', 'WCHAR_T');
    let buf = setter.convert(s + '\0');
    buf.type = wchar_t.string;
    return buf;
}
console.log(WCString('123'));

let res = show(CString('öä'), WCString('täst'));
console.log('normal', res);
*/


// async compilation
state.compileAsync(gen.code(), (res, err) => {
    console.log('we got here!', res, err);

    console.log('relocate', state.relocate());
    console.log(state.getSymbol('show'));
    console.log(gen.bindState(state));

    function CString(s, encoding) {
        let buf = new Buffer(s + '\0', encoding);
        buf.type = ref.types.CString;
        return buf;
    }

    function WCString(s, encoding) {
        const Iconv = require('iconv').Iconv;
        let setter = new Iconv(encoding || 'UTF-8', 'WCHAR_T');
        let buf = setter.convert(s + '\0');
        buf.type = wchar_t.string;
        return buf;
    }
    console.log(WCString('123'));

    let result = show(CString('öä'), WCString('täst'));
    console.log('normal', result);

});
