<template>
  <q-card :style="dialogStyle">
    <div id="barcode-scanner" :style="style"></div>
  </q-card>
</template>

<script setup lang="ts">
import { onMounted, computed } from 'vue';

const emit = defineEmits(['scanSuccess']);

const globalStore = window.PiniaStores.useGlobalStore();
const { html5QrcodeScanner } = window.Pinia.storeToRefs(globalStore);

const style = computed(() =>
  window.innerWidth > window.innerHeight ? 'width: 100vh' : 'width: 100vw',
);

const dialogStyle = computed(() =>
  window.innerWidth > window.innerHeight
    ? 'width: 100vh; min-width: 100vh; height: max-content'
    : 'width: 100vw; min-width: 100vw; height: max-content',
);

function onScanSuccess(decodedText, decodedResult) {
  // Handle on success condition with the decoded text or result.
  console.log(`Scan result: ${decodedText}`, decodedResult);
  // ...
  html5QrcodeScanner.value.clear();
  // Walmart QR labels
  if (decodedText.startsWith('w-mt.co')) {
    window.axios
      .post('/ws/ps/getWalmartLink.php', {
        shortLink: decodedText,
      })
      .then((response) => {
        const { data } = response;
        console.log(response);

        if (data && data.startsWith('http')) {
          const paths = new URL(data).pathname.split('/');
          if (paths.length) emit('scanSuccess', paths[paths.length - 1]);
        } else {
          emit('scanSuccess', '');
        }
      })
      .catch((err) => {
        console.error(err);
        emit('scanSuccess', '');
      });
  } else {
    // ^ this will stop the scanner (video feed) and clear the scan area.
    emit('scanSuccess', decodedText);
  }
}

onMounted(() => {
  if (!html5QrcodeScanner.value)
    html5QrcodeScanner.value = new window.Html5QrcodeScanner(
      'barcode-scanner',
      {
        fps: 10,
        qrbox: 250,
      },
    );

  html5QrcodeScanner.value.render(onScanSuccess);
});
</script>
