<!--
  - Copyright (c) 2022.
  - Author Peter Placzek (tada5hi)
  - For the full copyright and license information,
  - view the LICENSE file that was distributed with this source code.
  -->

<script>
import {addInvitation} from "@/domains/invitation/api";
import QrCodeGenerator from "@/components/qr-code/QrCodeGenerator";

export default {
    components: {QrCodeGenerator},
    props: {
        invitation: Object | undefined
    },
    data() {
        return {
            code: undefined,
            busy: false
        }
    },
    created() {
        this.init();
    },
    methods: {
        init() {
            if(this.invitation) {
                this.code = this.invitation.code;
            } else {
                this.generate();
            }
        },

        async generate() {
            if(typeof this.invitation !== 'undefined' || this.busy) return;

            this.busy = true;

            try {
                const invitation = await addInvitation();
                this.code = invitation.code;

                this.$emit('created', invitation);
            } catch (e) {
                this.$emit('failed', e.message);
            }

            this.busy = false;
        }
    },
    computed: {
        invitationExists() {
            return typeof this.invitation !== 'undefined';
        }
    }
}
</script>
<template>
    <form>
        <template v-if="!invitationExists">
            <p>
                Generiere einen Einladung um zusätzliche Personen die Nutzung der App zu ermöglichen oder
                eine Person zu deinen Kontakten hinzuzufügen.<br />
                Jeder QR-Code/Code kann dabei nur <strong>ein</strong> Mal genutzt werden.
            </p>
        </template>

        <template v-if="code">
            <h6>Text</h6>
            <div class="form-group">
                <input type="text" class="form-control" :disabled="true" v-model="code" placeholder="Code..." />
            </div>

            <h6>Qr-Code</h6>
            <div class="mb-2">
                <qr-code-generator v-if="code" :code="code" />
            </div>
        </template>
    </form>
</template>
