<template></template>
<script>
export default {
  name: 'ScannerOrReader',
  props: {
    enable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      code: '',
      lastTime: 0,
      nextTime: 0,
    }
  },
  watch: {
    enable(newValue, oldValue) {
      if (!oldValue && newValue) this.startListen()
      else if (oldValue && !newValue) this.stopListen()
    },
  },
  created() {
    if (this.enable) this.startListen()
  },
  destroyed() {
    this.stopListen()
  },
  methods: {
    startListen() {
      //console.log('startListen')
      this.lastTime = new Date().getTime()
      document.addEventListener('keydown', this.handleKeydown)
    },
    handleKeydown(e) {
      this.nextTime = new Date().getTime()
      if (this.nextTime - this.lastTime > 200) this.code = ''
      if (e.key == 'Enter') {
        if (this.code.length > 0) {
          //console.log('code:' + this.code)
          this.$emit('output', this.code)
          this.code = ''
        }
      } else {
        this.code += e.key
      }
      this.lastTime = this.nextTime
    },
    stopListen() {
      //console.log('stopListen')
      document.removeEventListener('keydown', this.handleKeydown)
    },
  },
}
</script>
