<!--
  - 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 copy from 'copy-to-clipboard';
import {dropInvitation, getInvitations} from "@/domains/invitation/api";
import InvitationBasicForm from '../../../components/invitation/InvitationBasicForm';
import ContactInvitation from "@/components/contact/ContactInvitation";
import Pagination from "~/components/Pagination";

export default {
    components: {
        Pagination,
        ContactInvitation,
        InvitationBasicForm
    },
    data() {
        return {
            item: undefined,
            itemBusy: false,
            items: [],
            meta: {
                limit: 10,
                offset: 0,
                total: 0
            },
            fields: [
                { key: 'id', label: 'ID', thClass: 'text-left', tdClass: 'text-left' },
                { key: 'created_at', label: 'Erstellt', thClass: 'text-center', tdClass: 'text-center' },
                { key: 'updated_at', label: 'Aktualisiert', thClass: 'text-left', tdClass: 'text-left' },
                { key: 'options', label: '', tdClass: 'text-left' }
            ],
            busy: false
        }
    },
    created() {
        this.load();
    },
    methods: {
        async load() {
            this.busy = true;

            try {
                const response = await getInvitations({
                    page: {
                        limit: this.meta.limit,
                        offset: this.meta.offset
                    }
                });

                this.items = response.data;
                const {total} = response.meta;

                this.meta.total = total;

                this.busy = false;
            } catch (e) {
                this.busy = false;
                throw e;
            }
        },
        goTo(options, resolve, reject) {
            if(options.offset === this.meta.offset) return;

            this.meta.offset = options.offset;

            this.load()
                .then(resolve)
                .catch(reject);
        },
        async add() {
            this.mode = 'add';
            this.item = undefined;

            this.$refs['form'].show();
        },
        async open(id) {
            this.mode = 'edit';
            this.item = this.items.filter((item) => item.id === id)[0];

            this.$refs['form'].show();
        },

        async drop(id) {
            if(this.itemBusy) return;

            this.itemBusy = true;

            try {
                await dropInvitation(id);
                const index = this.items.findIndex(item => item.id === id);
                if(invitations !== -1) {
                    this.items.splice(invitations, 1);
                }
            } catch (e) {

            }

            this.itemBusy = false;
        },

        copyToClipboard(code) {
            copy(code);

            this.$bvToast.toast('Einladunscode erfolgreich in die Zwischenablage kopiert');
        },

        handleCreated(e) {
            this.items.push(e);
        },

        acceptInvitation() {
            this.$refs['contactInvitation'].show();
        },
        async handleInvitationAccepted(contact) {
            this.$refs['contactInvitation'].hide();

            await this.$nuxt.$router.push('/contacts/'+contact.id);
        }
    }
}
</script>
<template>
    <div>
        <h5 class="title">
            Einladungen <i class="fa fa-user-plus"></i> <span class="sub-title">Das ist eine Übersicht aller erstellten Einladungen</span>
        </h5>
        <p>
            Einladungen können von registrierten Benutzern genutzt werden, um einen
            Kontakt mit dir zu erstellen.<br />
            Ebenso kann die Einladung zur Registrierung von neuen Benutzer verwendet werden.
        </p>
        <div class="d-flex flex-row mb-2">
            <div>
                <button @click.prevent="load" type="button" class="btn btn-xs btn-dark">
                    <i class="fas fa-sync"></i> Aktualisieren
                </button>
            </div>
            <div style="margin-left: auto;">
                <button @click.prevent="acceptInvitation" type="button" class="btn btn-xs btn-primary">
                    <i class="fa fa-check"></i> Annehmen
                </button>
                <button @click.prevent="add" type="button" class="btn btn-xs btn-success">
                    <i class="fa fa-hammer"></i> Generieren
                </button>
            </div>
        </div>
        <b-table :items="items" :fields="fields" :busy="busy" head-variant="'dark'" outlined>
            <template v-slot:cell(created_at)="data">
                <timeago :datetime="data.item.createdAt" />
            </template>
            <template v-slot:cell(updated_at)="data">
                <timeago :datetime="data.item.updatedAt" />
            </template>

            <template v-slot:cell(options)="data">
                <button
                    @click.prevent="open(data.item.id)"
                    class="btn btn-xs btn-primary"
                    v-b-tooltip="'Details'"
                >
                    <i class="fa fa-bars"></i>
                </button>
                <button
                    @click.prevent="copyToClipboard(data.item.code)"
                    type="button"
                    class="btn btn-dark btn-xs"
                    title="Kopieren"
                    v-b-tooltip="'Kopieren'"
                >
                    <i class="fa fa-copy"></i>
                </button>
                <button
                    @click.prevent="drop(data.item.id)"
                    type="button"
                    class="btn btn-xs btn-secondary"
                    title="Löschen"
                    v-b-tooltip="'Löschen'"
                >
                    <i class="fa fa-times"></i>
                </button>
            </template>


            <template v-slot:table-busy>
                <div class="text-center text-danger my-2">
                    <b-spinner class="align-middle" />
                    <strong>Loading...</strong>
                </div>
            </template>
        </b-table>
        <div class="alert alert-warning alert-sm" v-if="!busy && items.length === 0">
            Es sind keine Chat-Räume vorhanden...
        </div>
        <pagination v-if="!busy && items.length > 0" :total="meta.total" :offset="meta.offset" :limit="meta.limit" @to="goTo" />

        <b-modal
            size="lg"
            ref="form"
            button-size="sm"
            title-html="<i class='fas fa-user-plus'></i> Einladung"
            :no-close-on-backdrop="true"
            :ok-only="true"
            :no-close-on-esc="true"
        >
            <invitation-basic-form :invitation="item" @created="handleCreated"/>
        </b-modal>
        <b-modal
            size="lg"
            ref="contactInvitation"
            button-size="sm"
            title-html="<i class='fas fa-user-plus'></i> Einladung annehmen"
            :no-close-on-backdrop="true"
            :ok-only="true"
            :no-close-on-esc="true"
        >
            <contact-invitation @created="handleInvitationAccepted" />
        </b-modal>
    </div>
</template>
