// replace list variables in a DOCX template

import { CreateDocx, ListNested } from "../../../build";
import * as fs from "fs";

const docxTemplate = fs.readFileSync("../../files/TemplateVariablesList.docx");

const docx = new CreateDocx();
// load the template
docx.openTemplate(docxTemplate).then(docx => {
    const itemsA: ListNested = [
        "Item 1",
        "Item 2",
        ["Item A", "Item B", "Item C", ["Item C.1", "Item C.2"]],
        "Item 3",
        "Item 4",
        "Item 5",
    ];

    // variables to be replaced in the document
    const variablesDocumentA = new Map<string, ListNested[]>();
    variablesDocumentA.set("LISTVAR_BODY_BULLET", itemsA);
    variablesDocumentA.set("LISTVAR_BODY_CUSTOM", itemsA);

    // replace variables in the document target
    docx.replaceVariableList(variablesDocumentA);

    // replace a list with line breaks
    const itemsB: ListNested = [
        "Item 1",
        "Item 2",
        ["Item \n2.A &", "Item \n2.B", "Item \n2.C"],
        "Item 3",
        "Item 4",
        "Item 5",
    ];

    const variablesDocumentB = new Map<string, ListNested[]>();
    variablesDocumentB.set("LISTVAR_BODY_NUMBERING", itemsB);

    // replace variables in the document target setting options
    docx.replaceVariableList(variablesDocumentB);

    const itemsHeader: ListNested = [
        "Item header 1",
        "Item header 2",
        "Item header 3",
    ];

    // variables to be replaced in the header target
    const variablesHeader = new Map<string, ListNested[]>();
    variablesHeader.set("LISTVAR_HEADER", itemsHeader);

    // replace template variables in the header target
    docx.replaceVariableList(variablesHeader, "header");

    const itemsFooter: ListNested = [
        "Item footer 1",
        "Item footer 2",
        "Item footer 3",
    ];

    // variables to be replaced in the footer target
    const variablesFooter = new Map<string, ListNested[]>();
    variablesFooter.set("LISTVAR_FOOTER", itemsFooter);

    // replace template variables in the footer target
    docx.replaceVariableList(variablesFooter, "footer");

    // save the DOCX
    docx.save().then(contents => {
        fs.writeFileSync("replaceVariableList_1.docx", Buffer.from(contents));
    });
});
