<template>
  <div class="scanner-input">
    <b-input v-model="quickEntry"
             placeholder="Scan/Enter Code"
             icon="search"
             @keypress.native="quickKey">
    </b-input>
  </div>
</template>

<script>
export default {
    name: 'ByjoveScannerInput',
    data() {
        return {
            quickEntry: '',
        }
    },
    mounted() {
        window.addEventListener('keypress', this.globalKey)
    },
    beforeDestroy() {
        window.removeEventListener('keypress', this.globalKey)
    },

    methods: {

        globalKey(event) {
            if (event.target.tagName == 'BODY') {

                // mimic keyboard wedge
                if (event.charCode >= 48 && event.charCode <= 57) { // numeric (qwerty)
                    this.$nextTick(() => {
                        this.quickEntry += event.key
                    })

                } else if (event.keyCode == 13) { // enter
                    this.submitQuickEntry()
                }
            }
        },

        quickKey(event) {
            if (event.keyCode == 13) { // enter
                this.submitQuickEntry()
            }
        },

        submitQuickEntry() {
            if (this.quickEntry) {
                this.$emit('submit', this.quickEntry)
            }
        },
    },
}
</script>
