import bwipjs from 'bwip-js';


export function paymentQRCode(account, amount, currencyCode, message, identificator) {
    let sj = [];
    sj.push("SPD");
    sj.push("1.0");
    sj.push("ACC:" + account);
    sj.push("AM:" + num(amount, 2));
    sj.push("CC:" + currencyCode);
    if (message) {
        sj.push("MSG:" + message);
    }
    if (identificator) {
        sj.push("X-VS:" + identificator);
    }

    return _renderCode({
        bcid: 'qrcode',
        text: sj.join("*"),
        scale: 3,
        width: 64,
        height: 64,
        eclevel: "Q"
    });
}


export function codabarCode(content, width, height) {
    return _renderCode({ 
        bcid: 'code93ext',
        text: content,
        scale: 3,
        width: width || 35,
        height: height || 10,
    });
}



function _renderCode(options) {
    return new Promise((resolve, reject) => {
        let canvas = document.createElement('canvas');
        bwipjs(canvas, options, function(err, cvs) {
            if (err) {
                console.error(canvas, options, err);
                reject(err);
            } else {
                let data = canvas.toDataURL('image/png');
                resolve(data);
            }
        });

    });
}



export function num(s, places) {
    let n = isNaN(s) ? 0 : s * 1;
    if (places) {
        n = round(n, places);
    }
    return n * 1;
}

export function round(num, places) { 
    return +(Math.round(num + "e+" + places)  + "e-" + places);
}