<template>
  <div class="container">
    <p class="error">{{ error }}</p>
    <qrcode-stream @decode="onDecode" @init="onInit" />
  </div>
</template>

<script>
import { QrcodeStream } from 'vue-qrcode-reader'

export default {
  name: 'QRReader',
  components: {
    QrcodeStream
  },
  data () {
    return {
      result: '',
      error: ''
    }
  },
  methods: {
    onDecode (result) {
      this.result = result
      this.$emit('get-code', this.result)
    },
    async onInit (promise) {
      try {
        await promise
      } catch (error) {
        if (error.name === 'NotAllowedError') {
          this.error = 'Missing camera permissions'
        } else if (error.name === 'NotFoundError') {
          this.error = 'No camera'
        } else if (error.name === 'NotSupportedError') {
          this.error = 'https ?'
        } else if (error.name === 'NotReadableError') {
          this.error = 'Camera in use'
        } else if (error.name === 'OverconstrainedError') {
          this.error = 'Shitty camera'
        } else if (error.name === 'StreamApiNotSupportedError') {
          this.error = 'Shitty browser'
        }
      }
    },
    showAlert (message) {
      this.$buefy.dialog.alert({
        title: 'Erreur',
        message: message,
        type: 'is-danger',
        hasIcon: true,
        icon: 'alert-circle-outline',
        iconPack: 'mdi',
        ariaRole: 'alertdialog',
        ariaModal: true
      })
    }
  }
}
</script>

<style scoped>
.error {
  font-weight: bold;
  color: red;
}
</style>
