<kiss-container class="kiss-margin">

    <ul class="kiss-breadcrumbs">
        <li><a href="<?=$this->route('/detektivo')?>"><?=t('Detektivo')?></a></li>
        <li><span><?= $this->escape($index['label'] ? $index['label'] : $index['name']) ?></span></li>
    </ul>


    <vue-view class="kiss-margin">
        <template>

            <kiss-row class="kiss-flex-middle">
                <div>
                    <div class="kiss-color-muted"><kiss-svg :style="{color: index.color || 'inherit' }" :src="$baseUrl(type.icon || 'detektivo:assets/icons/index.svg')" width="50" height="50"></kiss-svg></div>
                </div>
                <div class="kiss-flex kiss-flex-middle kiss-flex-1">
                    <div>
                        <div class="kiss-size-4 kiss-text-bold kiss-flex kiss-flex-middle">
                            <div class="kiss-margin-end">{{ index.label || index.name }}</div>
                        </div>
                        <div>
                            <span class="kiss-text-caption kiss-color-muted">{{ index.type }}</span>
                        </div>
                    </div>
                    <div class="kiss-size-4 kiss-margin-start">
                        <a class="kiss-margin-small-end" kiss-tooltip="bottom" :aria-label="t('Copy index name')" @click="copyIndexName()"><icon>content_copy</icon></a>
                        <a class="kiss-margin-small-end" kiss-tooltip="bottom" :aria-label="t('Refresh')" @click="search()"><icon>refresh</icon></a>
                    </div>
                </div>
            </kiss-row>

            <form class="kiss-flex kiss-flex-middle kiss-margin" :class="{'kiss-disabled': loading}" @submit.prevent="search">

                <input type="text" class="kiss-input kiss-flex-1 kiss-margin-xsmall-end" :placeholder="t('Search...')" v-model="query">

                <div class="kiss-button-group kiss-margin-small-start" v-if="query">
                    <button type="button" class="kiss-button" @click="query = ''"><?= t('Reset') ?></button>
                </div>

            </form>

            <app-scrollcontainer mode="boundary-include" boundary="#idx-actionbar">

                <app-loader v-if="loading"></app-loader>

                <div class="animated fadeIn kiss-height-50vh kiss-flex kiss-flex-middle kiss-flex-center kiss-align-center kiss-color-muted" v-if="!loading && result && !result.total">
                    <div>
                        <kiss-svg :src="$baseUrl('detektivo:assets/icons/index.svg')" width="40" height="40"><canvas width="40" height="40"></canvas></kiss-svg>
                        <p class="kiss-size-large kiss-margin-small-top"><?=t('No records yet')?></p>
                    </div>
                </div>

                <div class="animated fadeIn kiss-height-50vh kiss-flex kiss-flex-middle kiss-flex-center kiss-align-center kiss-color-muted" v-if="!loading && result && result.total && !result.estimatedTotalHits">
                    <div>
                        <kiss-svg :src="$baseUrl('detektivo:assets/icons/index.svg')" width="40" height="40"><canvas width="40" height="40"></canvas></kiss-svg>
                        <p class="kiss-size-large kiss-margin-small-top"><?=t('No records found')?></p>
                    </div>
                </div>

                <div v-if="!loading && result && result.hits.length">

                    <kiss-card class="kiss-padding kiss-flex kiss-margin-small" theme="bordered" hover="shadow contrast" v-for="hit in result.hits">
                        <div class="kiss-margin-end" style="width:60px;">
                            <a @click="edit(hit)"><span class="kiss-badge kiss-align-center kiss-display-inline-block kiss-text-truncate"><icon>edit</icon> {{ hit.id }}</span></a>
                        </div>
                        <div class="kiss-flex-1 kiss-margin-end kiss-overflow-y-auto" style="max-height:20vh">
                            <div class="kiss-margin-small" v-for="field in getHitFields(hit)">
                                <div class="kiss-text-caption kiss-color-muted">{{ field }}</div>
                                <div class="kiss-size-small kiss-text-monospace">{{ hit[field] }}</div>
                            </div>
                        </div>
                        <div><a class="kiss-color-danger"@click="remove(hit)"><icon>delete</icon></a></div>
                    </kiss-card>

                </div>

            </app-scrollcontainer>


            <app-actionbar id="idx-actionbar" space="false">

                <kiss-container>
                    <div class="kiss-flex kiss-flex-middle">
                        <div class="kiss-button-group kiss-margin-end">
                            <button class="kiss-button" @click="addRecords()"><?=t('Add records')?></button>
                            <button class="kiss-button kiss-button-danger" @click="emptyIndex()" v-if="result && result.estimatedTotalHits"><?=t('Empty index')?></button>
                        </div>
                        <div class="kiss-flex kiss-flex-middle kiss-margin-end" v-if="!loading && result && result.estimatedTotalHits">
                            <app-pagination>
                                <div class="kiss-color-muted">{{ `${result.total} ${result.estimatedTotalHits == 1 ? t('Record') : t('Records')}` }}</div>
                                <a class="kiss-margin-small-start" v-if="(page - 1) >= 1" @click="search(page - 1)"><?= t('Previous') ?></a>
                                <div class="kiss-margin-small-start kiss-overlay-input" v-if="result.estimatedTotalHits > limit">
                                    <strong>{{ page }} &mdash; {{pages}}</strong>
                                    <select v-model="page" @change="search(page)" v-if="pages > 1">
                                        <option v-for="p in pages" :value="p">{{ p }}</option>
                                    </select>
                                </div>
                                <a class="kiss-margin-small-start" v-if="(page + 1) <= pages" @click="search(page + 1)"><?= t('Next') ?></a>
                            </app-pagination>
                        </div>
                        <div class="kiss-size-small kiss-flex-inline kiss-flex-middle kiss-margin-end" v-if="!loading && result">
                            <icon class="kiss-margin-xsmall-end" size="larger">timer</icon> {{ Math.floor(result.processingTimeMs < 1 ? 1 : result.processingTimeMs) }}ms
                        </div>
                        <div class="kiss-flex-1"></div>
                        <div class="kiss-button-group">
                            <a class="kiss-button kiss-button-primary" :href="$routeUrl(`/detektivo/idx/${index.name}/run`)" v-if="type.index"><?=('Re-Index')?></a>
                            <a class="kiss-button" href="<?=$this->route('/detektivo')?>">
                                <?=t('Close')?>
                            </a>
                        </div>
                    </div>
                </kiss-container>

            </app-actionbar>


        </template>

        <script type="module">

            export default {

                data() {
                    return {
                        index: <?=json_encode($index) ?>,
                        type: <?=json_encode($type) ?>,
                        loading: true,
                        query: '',
                        result: null,

                        page: 1,
                        pages: 1,
                        limit: 20,
                    }
                },

                mounted() {
                    this.search();
                },

                watch: {
                    query: {
                        handler: KISS.utils.debounce(function() {
                            this.search();
                        }, 300)
                    }
                },

                methods: {

                    getHitFields(hit) {
                        return this.index.fields.filter(field => (hit[field] !== undefined && hit[field] !== null && hit[field] !== ''));
                    },

                    addRecords() {
                        VueView.ui.modal('detektivo:assets/dialogs/add-records.js', {index: this.index}, {
                            'index:imported': () => {
                                this.search();
                            }
                        }, {escape:true});
                    },

                    remove(record) {

                        App.ui.confirm('Are you sure?', () => {

                            this.$request(`/detektivo/idx/remove/${this.index.name}/${record.id}`, {}).then(result => {
                                App.ui.notify('Document removed!');
                                this.search(this.result.hits.length == 1 && this.page > 1 ? this.page - 1 : this.page);
                            }).catch((res) => {
                                App.ui.notify(res.error || 'Removing failed!', 'error');
                            });
                        });
                    },

                    emptyIndex() {

                        App.ui.confirm('Are you sure?', () => {

                            this.$request(`/detektivo/idx/clear/${this.index.name}`, {}).then(result => {
                                App.ui.notify('Index emptied!');
                                this.search();
                            }).catch((res) => {
                                App.ui.notify(res.error || 'Something went wrong!', 'error');
                            });
                        });
                    },

                    edit(document) {
                        VueView.ui.offcanvas('detektivo:assets/dialogs/edit-record.js', {index: this.index, document});
                    },

                    search(page = 1) {

                        const offset = (page - 1) * this.limit;

                        this.loading = true;

                        this.$request(`/detektivo/search/${this.index.name}`, {q: this.query, limit: this.limit, offset}).then(result => {

                            this.loading = false;
                            this.result = result;
                            this.page = result.page;
                            this.pages = result.pages;

                        }).catch((err) => {

                            this.loading = false;
                            console.log(err);
                        })
                    },

                    copyIndexName() {
                        App.utils.copyText(this.index.name, () =>  App.ui.notify('Index name copied to clipboard!'));
                    }
                }
            }

        </script>
    </vue-view>
</kiss-container>
