<template>
  <div class="w-full md:max-w-md">
    <XMarkIcon class="ml-auto mb-2 w-5 h-5 cursor-pointer" @click="closeModal" />
    <qrcode-stream
      :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 { mapState, mapActions } from "pinia";
import { useModalStore } from "@/stores/modal";
import {
  barcodeFormats,
  defaultConstraintOptions,
  getAvailableCameras,
  handleScannerError,
  trackFunctionOptions,
  type Camera,
} from "@/helpers/codeScanner";
import { QrcodeStream, type DetectedBarcode } from "vue-qrcode-reader";
import { XMarkIcon } from "@heroicons/vue/24/outline";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    callback: {
      type: Function,
      default: (result: string) => {},
    },
  },
  data() {
    return {
      selecteableCameras: defaultConstraintOptions,
      selectedCamera: undefined as undefined | Camera,
      paused: false,
      detected: "",
    };
  },
  methods: {
    ...mapActions(useModalStore, ["closeModal"]),
    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.callback(this.detected);
      this.closeModal();
    },
  },
});
</script>
