const fs = require('fs');
const iconv = require('iconv-lite');

const typeMap = {
    string: 'std::string',
    Number: 'int'
}

function getType(t){
    let tp = (t?.type?.names[0] || '').replace(/^Array\.\<(.*)\>$/, '$1*')
    return typeMap[tp] || tp;
}

function graft(childNodes, parentLongname) {
    let result = '';
    childNodes.filter(({memberof}) => memberof === parentLongname)
    .forEach(element => {
        if (element.kind === 'function') {
            result += `/* ${element.description} */ ${getType(element.returns?.[0]) || 'void'} ${element.name}(${ element.params?.map(p=>
                `/* ${p.description || ''} */ ${getType(p)} ${p.name}`
            ).join(', ') || ''});\n`;
        }
        else if (element.kind === 'member') {
            result += `  /* ${element.description || ''} */ ${getType(element)} ${element.name};\n`
        }
        
        else if (element.kind === 'class') {
            result+= `/** ${element.classdesc || ''} */\nclass ${element.name}{\n public: \n`;
            result += graft(childNodes, element.longname);
            result+= '\n};\n';
       }
    });
    return result;
}

/**
    @param {TAFFY} data
    @param {object} opts
 */
exports.publish = (data, {destination, query}) => {
    let docs;

    data({undocumented: true}).remove();
    docs = data().get(); // <-- an array of Doclet objects

    fs.promises.writeFile(destination+'.json', JSON.stringify(docs, null, 2), {encoding:'utf-8'})
    
    let result = `#include <string>\n\n` + graft(docs);
    //console.log(result)
    fs.promises.writeFile(destination, iconv.encode(result, 'win1251'), {encoding: 'binary'});
};
