<template>
  <div v-if="!inUse" class="relative flex flex-col w-full h-[455px] overflow-hidden">
    <br />
    <button primary @click="startSession">Smartphone als Scanner verwenden</button>
  </div>
  <div v-else class="relative flex flex-col w-full h-[455px] overflow-hidden">
    <br />

    <div class="grow flex flex-col gap-2 overflow-y-scroll pr-2">
      <div
        v-for="i in results"
        :key="i"
        class="h-10 w-full flex justify-center items-center gap-2 py-2 px-4 text-sm font-medium rounded-md text-white bg-primary"
      >
        <p class="grow">{{ i }}</p>
        <TrashIcon class="w-5 h-5 cursor-pointer" @click="() => removeElementFromResults(i)" />
        <ArrowRightIcon class="w-5 h-5 cursor-pointer" @click="commit(i)" />
      </div>
      <p v-if="results.length == 0">Bisher keine Scan-Ergebnisse vorhanden.</p>
    </div>
    <br />
    <RouterLink :to="{ name: 'public-scanner-select' }" target="_blank" class="text-primary"
      >Link zur Scanoberfläche:</RouterLink
    >
    <div class="flex flex-row gap-4 items-center">
      <TextCopy :copyText="roomId" />
      <QrCodeIcon class="h-7 w-7 cursor-pointer" @click="showQRCode = true" />
    </div>

    <div v-show="showQRCode" class="absolute w-full h-full flex items-center justify-center bg-white/95 p-2">
      <img ref="qr" />
      <QrCodeIcon class="absolute bottom-1 right-0 h-7 w-7 cursor-pointer" @click="showQRCode = false" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState } from "pinia";
import { useScannerStore } from "../../stores/admin/scanner";
import { ArrowRightIcon, QrCodeIcon, TrashIcon } from "@heroicons/vue/24/outline";
import TextCopy from "../TextCopy.vue";
import QRCode from "qrcode";
import { RouterLink } from "vue-router";
</script>

<script lang="ts">
export default defineComponent({
  emits: ["code"],
  data() {
    return {
      showQRCode: false as boolean,
    };
  },
  computed: {
    ...mapState(useScannerStore, ["inUse", "roomId", "results"]),
    linkToScan() {
      return `${window.location.origin}/public/scanner/${this.roomId}`;
    },
  },
  mounted() {
    QRCode.toDataURL(this.linkToScan, {
      width: 300,
      margin: 2,
      color: {
        dark: "#000000",
        light: "#FFFFFF",
      },
      errorCorrectionLevel: "M",
    })
      .then((res) => {
        (this.$refs.qr as HTMLImageElement).src = res;
      })
      .catch(() => {});
  },
  methods: {
    ...mapActions(useScannerStore, ["startSession", "endSession", "removeElementFromResults"]),
    commit(c: string) {
      this.$emit("code", c);
    },
  },
});
</script>
