// replace image variables in a DOCX template setting custom options

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

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

const docx = new CreateDocx();
// load the template
docx.openTemplate(docxTemplate).then(docx => {
    const fileJpgA = fs.readFileSync("../../files/image.jpg");

    // variables to be replaced in the document target
    let variablesDocument = new Map<string, ArrayBuffer>();
    variablesDocument.set("IMAGE_1", fileJpgA);

    // replace template image variables in the document target
    const optionsReplaceVariableImageA: OptionsReplaceVariableImage = {
        firstMatch: true,
        height: -1,
        width: -1,
    };
    docx.replaceVariableImage(
        variablesDocument,
        "document",
        optionsReplaceVariableImageA
    );

    const filePng = fs.readFileSync("../../files/image.png");

    // variables to be replaced in the document target
    variablesDocument = new Map<string, ArrayBuffer>();
    variablesDocument.set("IMAGE_2", filePng);

    // replace template image variables setting new width and height sizes
    const optionsReplaceVariableImageB: OptionsReplaceVariableImage = {
        height: 3200000,
        width: 3200000,
    };
    docx.replaceVariableImage(
        variablesDocument,
        "document",
        optionsReplaceVariableImageB
    );

    // variables to be replaced in the header target
    const variablesHeader = new Map<string, ArrayBuffer>();
    variablesHeader.set("HEADERIMG", fileJpgA);

    const optionsReplaceVariableImageHeader: OptionsReplaceVariableImage = {
        height: -1,
        width: -1,
    };

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

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