export default {

    _meta: { size: 'large' },

    data() {

        return {
            mode: 'init',
            filename: '',
            uuid: App.utils.uuid(),
            loading: false,
            uploading: false,
            progress: 0,
            records: [],
        }
    },

    props: {

        index: {
            type: Object,
            default: null
        },
    },

    mounted() {

    },

    methods: {

        initManual() {
            let record = {};
            this.index.fields.forEach(field => record[field] = '...');
            this.records = [record];
            this.mode = 'edit';
        },

        readContents(files) {

            if (!files || !files.length) return;

            const file = files[0];
            const reader = new FileReader();

            reader.onload = (e) => {
                try {
                    const content = JSON.parse(e.target.result);

                    if (Array.isArray(content)) {
                        this.records = content;
                        this.filename = file.name;
                        this.mode = 'upload';
                        App.ui.notify('File loaded!');
                    } else {
                        App.ui.notify('Invalid file format. Expecting an array of objects.', 'error');
                    }
                } catch (e) {
                    App.ui.notify('Invalid JSON file', 'error');
                }
            };

            reader.readAsText(file);
        },

        importRecords() {

            this.loading = true;
            this.progress = 0;

            const sendChunksSequentially = (array, size = 50, onProgress) => {

                let chunks = [];

                for (let i = 0; i < array.length; i += size) {
                    chunks.push(array.slice(i, i + size));
                }

                return chunks.reduce(
                    (promise, chunk, index) => {
                        return promise
                            .then(() => this.$request(`/detektivo/idx/import/${this.index.name}`, { items: chunk }))
                            .then(() => {
                                if (onProgress) onProgress(Math.round(((index + 1) / chunks.length) * 100))
                            });
                    },
                    Promise.resolve()
                );
            }

            sendChunksSequentially(this.records, 50, (progress) => this.progress = progress).then(() => {

                this.loading = false;
                App.ui.notify('Records imported!');

                this.$call('index:imported', true);
                this.$close();

            }).catch(res => {

                this.loading = false;
                App.ui.notify(res.error || 'Importing records failed!', 'error');
            });
        }
    },


    template: /*html*/`
        <div>

            <div class="kiss-margin">
                <span class="kiss-size-xsmall kiss-color-muted kiss-text-upper">{{ index.label || index.name }}</span>
                <div class="kiss-size-4 kiss-text-bold">{{ t('Add records') }}</div>
            </div>

            <kiss-grid cols="2@m" class="kiss-margin" gap v-if="mode=='init'">   

                <kiss-card class="kiss-padding-large kiss-align-center kiss-cursor-pointer" theme="bordered" hover="contrast bordered-primary" @click="initManual()">
                    <div class="kiss-size-xlarge kiss-margin-small"><icon>edit</icon></div>
                    <div class="kiss-text-bold">{{ t('Manual Entry') }}</div>
                </kiss-card>

                <kiss-card class="kiss-padding-large kiss-align-center kiss-cursor-pointer kiss-overlay-input" theme="bordered" hover="contrast bordered-primary">
                    <input type="file" name="file" accept=".json" @change="(e) => {readContents(e.target.files)}" />
                    <div class="kiss-size-xlarge kiss-margin-small"><icon>upload</icon></div>
                    <div class="kiss-text-bold">{{ t('Upload File') }}</div>
                </kiss-card>

            </kiss-grid>

            <button type="button" class="kiss-button kiss-width-1-1" kiss-dialog-close v-if="mode=='init'">{{ t('Cancel') }}</button>

            <div v-if="mode=='upload'">

                <div class="kiss-margin kiss-align-center kiss-padding-large">
                    <div class="kiss-size-1 kiss-margin-small"><icon>text_snippet</icon></div>
                    <div class="kiss-text-bold">{{ filename }}</div>
                    <div class="kiss-color-muted">{{ records.length }} {{ records.length === 1 ? t('Record') : t('Records') }} {{ t('found') }}</div>
                </div>

                <div :class="{'kiss-disabled':loading}">
                    <div class="kiss-flex kiss-flex-middle">
                        <button class="kiss-button kiss-margin-end" @click="mode='init'" :disabled="loading">{{ t('Back') }}</button>
                        <div class="kiss-size-xsmall kiss-text-bold" v-if="loading && progress">{{ progress }}%</div>
                        <div class="kiss-flex-1 kiss-margin-end"></div>
                        <div class="kiss-button-group">
                            <button class="kiss-button kiss-button-primary" @click="importRecords()">{{ t('Import') }}</button>
                            <button class="kiss-button" kiss-dialog-close>{{ t('Close') }}</button>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="mode=='edit'">

                <div class="kiss-margin" :class="{'kiss-disabled':loading}">
                    <label>{{ t('Records') }}</label>
                    <field-object v-model="records" :height="auto"></field-object>
                </div>

                <div :class="{'kiss-disabled':loading}">
                    <div class="kiss-flex kiss-flex-middle">
                        <button class="kiss-button kiss-margin-end" @click="mode='init'" :disabled="loading">{{ t('Back') }}</button>
                        <div class="kiss-size-xsmall kiss-text-bold" v-if="loading && progress">{{ progress }}%</div>
                        <div class="kiss-flex-1 kiss-margin-end"></div>
                        <div class="kiss-size-xsmall kiss-color-muted kiss-margin-end" v-if="Array.isArray(records) && records.length">
                            {{ records.length }} {{ records.length === 1 ? t('Record') : t('Records') }}
                        </div>
                        <div class="kiss-button-group">
                            <button class="kiss-button kiss-button-primary" :class="{'kiss-disabled':!(Array.isArray(records) && records.length)}" @click="importRecords()">{{ t('Import') }}</button>
                            <button class="kiss-button" autofocus kiss-dialog-close>{{ t('Close') }}</button>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    `
}
