import AsyncHelpers from "async-helpers";
import bwipjs from "bwip-js";

export const asyncHelpers = new AsyncHelpers();
async function generateBarcode(str, options, emtpy, cb) {
    if (str == null) { cb(null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="); return; }
    let res = await generateBase64Barcode(options.toString(), str.toString());
    cb(null, res);
}
generateBarcode.async = true;
asyncHelpers.set('--bc', generateBarcode);
export const helpers = asyncHelpers.get({ wrap: true });

export async function generateBase64Barcode(type: string, content: string): Promise<String> {
    let options = {
        bcid: type,
        text: content,
        scale: 4,
        height: 10,
        width: 10,
        includetext: true,
        textxalign: 'center'
    }
    if (type != "qrcode") {
        delete options.width;
    }
    try {
        const barcode: Buffer = await bwipjs.toBuffer(options);
        return `data:image/png;base64,${barcode.toString('base64')}`;
    }
    catch {
        return errorimage;
    }
}

export async function awaitAsyncHandlebarHelpers(input: string): Promise<string> {
    return await new Promise((resolve, reject) => {
        asyncHelpers.resolveIds(input, (err, data) => {
            if (err) { reject(err) }
            resolve(data)
        });
    });
}

const errorimage = "data:image/png;base64,[encoded data, 11792 characters]"