import * as bpac from "/js/libs/bpac.js";

export class PtouchPrinter {
    constructor(object) {
        this.object = object;
        this.pdocument = bpac.IDocument;
    }

    async print() {
        if (!bpac.IsExtensionInstalled()) {
            console.error("L'extension b-Pac n'est pas installée");
            return -1;
        }

        try {
            await this.openDoc();
            await this.fillDoc();
            this.printDoc();
            this.pdocument.Close();

            return 1;
        } catch (e) {
            console.log(e);
            return 99;
        }
    };

    async openDoc() {
        const docUrl = `${baseUrl}/lbx/${this.object.template}.lbx`;
        console.log("Ouverture du modèle: " + docUrl);
        await this.pdocument.Open(docUrl);
    }

    async fillDoc() {
        for (let i = 0; i < this.object.lines.length; i++) {
            const line = this.object.lines[i];
            const label = await this.pdocument.GetObject(line.name);
            label.Text = line.value;
        }
    }

    printDoc() {
        this.pdocument.StartPrint("", 0);
        this.pdocument.PrintOut(1, 0);
        this.pdocument.EndPrint();
    }
}
