<template>
  <div class="flex flex-col gap-2 w-full min-h-[455px]">
    <qrcode-stream
      class="grow"
      :constraints="selectedCamera?.constraints"
      :track="trackFunctionOptions[4].value"
      :formats="barcodeFormats"
      :paused="paused"
      @error="onError"
      @detect="onDetect"
      @camera-on="onCameraReady"
    />
    <br />
    <select v-model="selectedCamera">
      <option v-for="c in selecteableCameras" :value="c">{{ c.label }}</option>
    </select>
    <div class="flex flex-row justify-end gap-4 py-2">
      <button primary-outline @click="paused = false" :disabled="!paused">weiter scannen</button>
      <button primary-outline @click="commit">bestätigen</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import {
  barcodeFormats,
  defaultConstraintOptions,
  getAvailableCameras,
  handleScannerError,
  trackFunctionOptions,
  type Camera,
} from "@/helpers/scanner";
import { QrcodeStream, type DetectedBarcode } from "vue-qrcode-reader";
</script>

<script lang="ts">
export default defineComponent({
  emits: ["code"],
  data() {
    return {
      selecteableCameras: defaultConstraintOptions,
      selectedCamera: undefined as undefined | Camera,
      paused: false,
      detected: "",
    };
  },
  methods: {
    async onCameraReady() {
      this.selecteableCameras = await getAvailableCameras();
      if (!this.selectedCamera) {
        this.selectedCamera = this.selecteableCameras[0];
      }
    },
    onDetect(result: Array<DetectedBarcode>) {
      this.paused = true;
      this.detected = result.map((r) => r.rawValue)[0];
    },
    onError(err: Error) {
      console.log(handleScannerError(err));
    },
    commit() {
      this.$emit("code", this.detected);
    },
  },
});
</script>
