// replace list variables with WordFragments in a DOCX template

import {
    CreateDocx,
    ListNested,
    OptionsDateTime,
    OptionsImage,
    OptionsLink,
    OptionsText,
    WordFragment,
} 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 => {
    // create a text WordFragment
    const wordFragmentText = new WordFragment();
    const text: OptionsText = {
        bold: true,
        italic: true,
        fontSize: 14,
        text: "Item 2.",
    };
    wordFragmentText.addText([text]);

    // create a link WordFragment
    const wordFragmentLink = new WordFragment();
    const link: OptionsLink = {
        link: "https://www.phpdocx.com",
        text: "phpdocx",
    };
    wordFragmentLink.addLink(link);

    // create a link WordFragment
    const wordFragmentLinkB = new WordFragment();
    const optionsLinkB: OptionsLink = {
        link: "https://www.phpxlsx.com",
        text: "phpxlsx",
    };
    wordFragmentLinkB.addLink(optionsLinkB);

    // create texts WordFragments
    const wordFragmentTextA = new WordFragment();
    wordFragmentTextA.addText("A link to ");
    const wordFragmentTextB = new WordFragment();
    wordFragmentTextB.addText(
        " in the middle of a paragraph with the following date: "
    );

    // create a date WordFragment
    const dateTime: OptionsDateTime = {
        format: "M/d/yyyy",
        bold: true,
        color: "333333",
    };
    const wordFragmentDate = new WordFragment();
    wordFragmentDate.addDateTime(dateTime);
    const wordFragmentTextComplex = new WordFragment();
    wordFragmentTextComplex.addText([
        wordFragmentTextA,
        wordFragmentLinkB,
        wordFragmentTextB,
        wordFragmentDate,
    ]);

    const fileJpg = fs.readFileSync("../../files/image.jpg");
    const wordFragmentImageA = new WordFragment();
    const imageJpg: OptionsImage = {
        image: fileJpg,
    };
    wordFragmentImageA.addImage(imageJpg);

    const itemsA: ListNested = [
        "Item 1",
        wordFragmentText,
        [
            "Item A",
            "Item B",
            wordFragmentTextComplex,
            [wordFragmentImageA, "Item C.2"],
        ],
        wordFragmentLink,
        "Item 4",
        "Item 5",
    ];

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

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

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