<script>
    import {onMount, tick, beforeUpdate} from 'svelte' ;

    let barcodeReady = false;
    let mounted = false;

    onMount(() => {
        // The payment-form is ready.
        mounted = true;
        //if (barcodeReady) {
        loadBarcodeElements();
        //}
    });

    //export const 

    const target = (bc) => bc.length < 9 ? 7 : 12;

    let error;

    $: format = barcode.length < 9 ? "EAN8" : "EAN13";


    function padBarcode(bc, length, pad = 0) {
        return bc;
        while (bc.length < length) {
            bc = pad + bc.toString();
        }

        return bc;
    }

    const loadBarcodeElements = () => {
        clearCanvas(document.getElementById("barcode").getContext("2d"));
        error = null;
        if (barcode != null && barcode.length > 0) {
            //bwipjs.toCanvas("barcode", {bcid:format, text: padBarcode(barcode, target(barcode))});
            try {

                const x = JsBarcode("#barcode", padBarcode(barcode, target(barcode)), {format: format});
                console.log(x);
            } catch {
                error = "Invalid barcode"
            }
        }
    };

    export let barcode = "";

    beforeUpdate(async () => {
        if (mounted) {
            loadBarcodeElements();
        }
        await tick();
    });

    export const appendCheckDigit = () => {
        if (barcode.length === 7 || barcode.length === 12) {
            const check = eanCheckDigit(barcode);
            //if (barcode[barcode.length-1] !== check)
            //{
            barcode += check;
            //}
        }
    };


    function clearCanvas(context, canvas = context.canvas) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        const w = canvas.width;
        canvas.width = 1;
        canvas.width = w;
    }

    // definitely a hack.
    export const eanCheckDigit = (s) => {
        let x = JsBarcode("#barcode", s, {format: format});

        //EAN barcodes by default have 5 parts (prefix -> left part -> middle seperator -> right part -> suffix)
        // we only want left & right part (which contain a text
        let calculated = "";
        x._encodings[0].filter(e => e.text !== "").forEach(e => calculated += e.text);
        console.log(calculated);
        return calculated[calculated.length - 1];
    }

</script>


<canvas id="barcode" width="50%" height="100%"></canvas>
{#if error}
    <p>Error: {error}</p>
{/if}

