import { defineComponent, onMounted, ref, toRef, watch, toRefs } from 'vue'
import { tools } from '@src/store/Modules/tools'

import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'

import JsBarcode from 'jsbarcode'

export default defineComponent({
  name: 'CBarCode',
  props: {
    value: {
      type: String,
      required: true,
    },
    format: {
      type: String,
      required: false,
      default: 'CODE128',
    },
    text: {
      type: String,
      required: false,
      default: '',
    },
    width: {
      type: Number,
      required: false,
      default: 50,
    },
    widthlines: {
      type: Number,
      required: false,
      default: 2,
    },
    show_at_right: {
      type: Boolean,
      required: false,
      default: false,
    },
    height: {
      type: String,
      required: false,
      default: '100',
    },
    gap: {
      type: String,
      required: false,
      default: '0',
    },
    fontsizeprop: {
      type: String,
      required: false,
      default: '16',
    },
  },
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n();

    // Converti le props in riferimenti reattivi
    const { value, format, width, widthlines, height, fontsizeprop } = toRefs(props);

    const fontsize = ref(<string>props.fontsizeprop)

    // Funzione per disegnare il codice a barre
    const drawBarcode = () => {
      try {
        if (value.value && value.value.length > 2) {
          JsBarcode("#C" + value.value, value.value, {
            format: (format.value || 'CODE128'),
            width: widthlines.value,
            height: tools.convstrToNum(height.value),
            displayValue: true,
            lineColor: "#000",
            font: "monospace",
            margin: 0,
            textMargin: 0,
            marginTop: 0,
            fontSize: tools.convstrToNum(fontsize.value),
            textPosition: "bottom",
          });
        }
      } catch (e) {

      }
    }

    // Chiamato quando il componente è montato
    onMounted(() => {
      drawBarcode();
    })

    // Watcher per aggiornamenti delle proprietà
    watch([value, format, width, height, fontsize], () => {
      drawBarcode();
    })

    return {
      tools,
      toolsext,
      fontsize,
    }
  },
})
