const Entities = require('html-entities').AllHtmlEntities;
const entities = new Entities();

module.exports.toXml = function (name, data) {
    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += '<extract>\n';
    xml += `\t<name>${entities.decode(name)}</name>\n`;
    xml += '\t<coauthors>\n';
    data.coauth.forEach(elt => {
        xml += `\t\t<author>${entities.decode(elt)}</author>\n`;
    });
    xml += '\t</coauthors>\n';
    // Articles
    for (let key in data.article) {
        const article = data.article[key];
        xml += `\t<article key="${entities.decode(key)}">\n`;
        article.auth.forEach(elt => {
            xml += `\t\t<author>${entities.decode(elt)}</author>\n`;
        });
        xml += `\t\t<title>${entities.decode(article.title)}</title>\n`;
        xml += `\t\t<year>${entities.decode(article.year)}</year>\n`;
        xml += '\t</article>\n';
    }
    // InProceeding
    for (let key in data.proceed) {
        const proceed = data.proceed[key];
        xml += `\t<inproceedings key="${entities.decode(key)}">\n`;
        proceed.auth.forEach(elt => {
            xml += `\t\t<author>${entities.decode(elt)}</author>\n`;
        });
        xml += `\t\t<title>${entities.decode(proceed.title)}</title>\n`;
        xml += `\t\t<year>${entities.decode(proceed.year)}</year>\n`;
        xml += '\t</inproceedings>\n';
    }
    xml += '</extract>\n';
    return xml;
};