<template>
  <div class="invalidation-view">
    <qrcode-stream
      v-if="!token"
      @decode="onDecode"
      @init="onInit">
    </qrcode-stream>
    <div v-else>
      <div v-if="status && !status.valid">
        reservation {{ token }} from {{status.anzeigename}} is not valid!<br>
        reason: {{status.reason || status.detail}}<br><br>
        <button @click="onReset" class="btn reset-btn">reset</button>
      </div>
      <div v-if="status && status.valid">
        reservation from {{status.anzeigename}} is valid :) <br>
        <div>
          <button @click="onInvalidate" class="btn invalidate-btn">invalidate now</button>
          <button @click="onReset" class="btn reset-btn">reset</button>
        </div>
        <div v-if="error">
          {{error}}
        </div>
      </div>
    </div>
    <!-- {{status}} -->
  </div>
</template>

<script>
import { QrcodeStream } from 'vue-qrcode-reader'
export default {
  name: 'Invalidate',
  components: {
    QrcodeStream,
  },
  data() {
    return {
      token: null,
      status: null,
      success: null,
      error: null,
    }
  },
  methods: {
    async onDecode(token) {
      this.token = token
      this.status = await this.getStatus(token)
    },
    async getStatus (token) {
      const response = await fetch(`${process.env.VUE_APP_API_URL}guest/${token}`)
      const data = await response.json()
      return data
    },
    onInit(promise) {
      promise
        .then(console.log)
        .catch(console.error)
    },
    onReset() {
      this.token = null
      this.status = null
      this.success = null
      this.error = null
    },
    async onInvalidate() {
      let data = {
        token: this.token
      }
      const response = await fetch(
        `${process.env.VUE_APP_API_URL}guest/invalidate`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data),
        }
      )
      if (response.status === 200) {
        this.success = true
        this.onReset()
      } else {
        this.error = await response.json()
      }
    }

  },
}
</script>

<style>
.invalidation-view {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}
.btn {
  padding: 1em;
  font-size: 2em;
  border: none;
  outline: none;
  margin: .2em 0;
}
.invalidate-btn {
  background: rgb(255, 255, 255);
  color: #000;
  margin-right: 1em;
}
.reset-btn {
  background: rgb(138, 138, 138);
  color: #000;
}

</style>