<template>
  <div class="form-group micro-barcode">
    <label :for="`inputBarCaption${_uid}`" v-if="caption">{{ caption }}</label>

    <div v-if="! scanning" @click="toggleScanning">
      <slot name="startScan">
        <a href="javascript:;" class="btn btn-primary btn-block">
          <span class="mdi mdi-barcode-scan"></span> 
          Start barcode scan
        </a>
      </slot>
    </div>
    <div v-else @click="toggleScanning">
      <slot name="stopScan">
        <a href="javascript:;" class="btn btn-danger btn-block">
          <span class="mdi mdi-barcode-scan"></span> 
          Stop barcode scan
        </a>
      </slot>
    </div>

    <div v-show="scanning" :id="`inputBarVideo${_uid}`" class="video-container-barcode mt-3 mb-3"></div>

    <table class="table" v-if="showResults" v-show="scanResults.length">
      <thead>
        <tr>
          <th scope="col">Value</th>
          <th scope="col">Format</th>
          <th scope="col">Scanned</th>
          <th scope="col">&nbsp;</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in scanResults" :key="`bc-${item.value}`">
          <td>{{ item.value }}</td>
          <td>{{ item.format }}</td>
          <td>{{ item._created | readable_time }}</td>
          <td class="text-right"><a href="javascript:;" class="text-danger" @click="scanResults.splice(index, 1) && $emit('input', scanResults)"><span class="mdi mdi-delete"></span></a></td>
        </tr>
      </tbody>
    </table>

    <small class="form-text text-muted">
      {{ description }}
    </small>
  </div>
</template>

<script>
  // https://github.com/serratus/quaggaJS
  import Quagga from 'quagga'
  import readableTime from 'readable-timestamp'

  export default {
    props: { 
      caption: String, 
      value: [ Object, Array ], 
      description: String, 
      placeholder: String, 
      field: Object, 
      continueAfterResult: Boolean, 
      autoStart: Boolean, 
      readers: Array,
      showResults: {
        type: Boolean,
        default: true,
      },
    },

    data() {
      return {
        hasCamera: false,
        scanner: null,
        scanning: false,
        scanResults: [],
        initParams: false,
      }
    },

    filters: {
      readable_time: function (value) {
        var d = new Date(value)
        return readableTime(d)
      },
    },

    mounted () {
      const vm = this

      vm.initParams = {
        inputStream : {
          size: 800,
          name : 'Live',
          type : 'LiveStream',
          target: document.querySelector(`#inputBarVideo${this._uid}`)
        },
        decoder : {
          readers : vm.readers || ['code_128_reader', 'ean_reader'],
        },
        numOfWorkers: 2,
        frequency: 2,
      }

      if (vm.autoStart) {
        vm.toggleScanning()
      }
    },

    beforeDestroy () {
      const vm = this
      if (vm.scanner) {
        vm.scanner.destroy()
      }
    },

    methods: {
      toggleScanning () {
        const vm = this

        if (vm.scanning) {
          Quagga.stop()
        } else {
          Quagga.init(vm.initParams, function(err) {
            if (err) {
              // console.log(err)
              return
            }

            Quagga.onDetected(ret => {
              // console.log(ret)
              let code = ret.codeResult.code
              let code_format = ret.codeResult.format
              let result_exists = false

              vm.scanResults.forEach(res => {
                if (res.value == code) {
                  result_exists = true
                  return false
                }
              })

              if (! result_exists) {
                vm.scanResults.push({
                  value: code,
                  format: code_format,
                  _created: new Date().getTime(),
                })

                vm.$emit('input', vm.scanResults)
              }

              if (! vm.continueAfterResult) {
                vm.toggleScanning()
              }
            })

            Quagga.start()
          })
        }

        vm.scanning = ! vm.scanning
      },

      handleInput(e) {
        this.$emit('input', e.target.value)
      },
    }
  }
</script>

<style lang="scss">
.micro-barcode {
  .video-container-barcode {
    video {
      width: 100%;
      height: 180px;
    }

    .drawingBuffer {
      display: none;
    }
  }
}
</style>