<template>
  <div class="barcode-label">
    <svg ref="svg" class="barcode-svg" />
    <div class="barcode-meta">
      <div class="barcode-id">{{ value }}</div>
      <div v-if="caption" class="barcode-caption">{{ caption }}</div>
    </div>
  </div>
</template>

<script>
import JsBarcode from 'jsbarcode';

export default {
  props: {
    value: { type: String, required: true },
    caption: { type: String, default: '' },
    format: { type: String, default: 'CODE128' }
  },
  mounted() {
    this.render();
  },
  watch: {
    value() {
      this.render();
    },
    format() {
      this.render();
    }
  },
  methods: {
    render() {
      const svg = this.$refs.svg;
      if (!svg || !this.value) return;
      try {
        JsBarcode(svg, this.value, {
          format: this.format,
          displayValue: false,
          margin: 0,
          height: 46,
          width: 1.6
        });
      } catch {
        // Value is not encodable in the chosen symbology; leave the SVG blank.
        svg.innerHTML = '';
      }
    }
  }
};
</script>
