<!--
  - 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>
export default {
    data() {
        return {
            busy: false,

            importMessage: undefined,

            form: {
                importType: 'text',
                importString: '',
            }
        }
    },
    methods: {
        async importKeys() {
            if(this.busy) return;

            this.busy = true;
            this.importMessage = undefined;

            try {
                await this.$security.importContactKeys(this.form.importString);
                this.importMessage = {
                    isError: false,
                    data: 'Die Schlüssel konnten erfolgreich importiert werden.'
                }
            } catch (e) {
                this.importMessage = {
                    isError: true,
                    data: e.message
                }
            }

            this.busy = false;
        },

        handleQrDecoded(value) {
            this.form.importString = value;
        },
        handleQrFailed(error) {

        }
    }
}
</script>
<template>
    <div>
        <h6><i class="fa fa-file-upload"></i> Import</h6>

        <div class="mb-1">
            <b-checkbox v-model="form.importType" :value="'text'">
                Text
            </b-checkbox>
            <b-checkbox v-model="form.importType" :value="'qr'">
                QR-Code
            </b-checkbox>
        </div>

        <template v-if="form.importType === 'text'">
            <div class="form-group">
                <label>Inhalt</label>
                <textarea rows="8" class="form-control" v-model="form.importString" placeholder="{
    contactSelfKeyPairs: {
        ...
    },
    contactRelatedKeys: {
        ...
    }
}">
                        </textarea>
            </div>
        </template>
        <template v-else-if="form.importType === 'qr'">
            <client-only>
                <qr-code-scanner @decoded="handleQrDecoded" @failed="handleQrFailed" />
            </client-only>
        </template>

        <hr />

        <template v-if="importMessage">
            <div
                class="alert alert-sm"
                :class="{'alert-danger': importMessage.isError, 'alert-success': !importMessage.isError}"
            >
                {{ importMessage.data }}
            </div>
        </template>

        <button type="button" class="btn btn-primary btn-xs" @click.prevent="importKeys">
            Importieren
        </button>
    </div>
</template>
