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

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

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

            <kiss-card :class="{'kiss-disabled': isRunning}" class="kiss-padding" theme="shadowed contrast">
                <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-1">
                        <div class="kiss-size-4 kiss-text-bold">
                            {{ index.label || index.name }}
                        </div>
                        <div>
                            <span class="kiss-text-caption kiss-color-muted">{{ index.type }}</span>
                        </div>
                    </div>
                </kiss-row>
            </kiss-card>

            <div class="kiss-text-caption kiss-text-bold kiss-color-muted kiss-margin" v-if="log.length"><?=t('Indexer log')?>:</div>

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

                <div class="animated fadeIn kiss-height-50vh kiss-flex kiss-flex-middle kiss-flex-center kiss-align-center kiss-color-muted" v-if="!isRunning && !log.length">
                    <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('Indexing not started yet')?></p>
                    </div>
                </div>

                <div class="kiss-margin" v-if="log.length">

                    <div class="kiss-size-small kiss-text-monospace kiss-flex kiss-margin-small" v-for="entry in infos">
                        <div class="kiss-text-bold kiss-color-muted kiss-margin-end" style="width:200px;">&mdash; {{ timeToDateTime(entry.time) }}</div>
                        <div class="iss-flex-1">{{ entry.msg }}</div>
                    </div>

                    <app-loader class="kiss-display-inline-block kiss-margin-small" mode="dots" v-if="isRunning"></app-loader>
                </div>


            </app-scrollcontainer>


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

                <kiss-container>
                    <div class="kiss-flex kiss-flex-middle">
                        <button class="kiss-button kiss-button-danger" @click="stop()" v-if="isRunning"><?=t('Stop indexer')?></button>
                        <div class="kiss-flex-1"></div>
                        <div class="kiss-button-group">
                            <button class="kiss-button kiss-button-primary" @click="start()" v-if="!isRunning"><?=('Start indexer')?></button>
                            <a class="kiss-button" href="<?=$this->route("/detektivo/idx/{$index['name']}")?>">
                                <?=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) ?>,
                        isRunning: <?=json_encode($isRunning) ?>,
                        log: [],
                    }
                },

                mounted() {

                    if (this.isRunning) {
                        this.getLog();
                    }
                },

                computed: {
                    infos() {
                        return this.log.filter(item => item.type === 'info');
                    },
                },

                methods: {

                    start() {

                        this.isRunning = true;
                        this.log = [];

                        this.$request(`/detektivo/idx/run/${this.index.name}/1`).then(res => {

                            this.log.push({
                                time: this.time(),
                                msg: 'Indexing started',
                                type: 'info',
                            });

                            this.getLog();

                        }).catch(res => {
                            App.ui.notify((res && res.error) || 'Something went wrong', 'error');
                        });
                    },

                    stop() {

                        App.ui.confirm('Are you sure you want to stop the indexer?', () => {

                            this.$request(`/detektivo/idx/stopRunner/${this.index.name}?nc=${Math.random()}`).then(res => {

                                this.isRunning = false;

                                this.log.push({
                                    time: this.time(),
                                    msg: 'Indexing stopped',
                                    type: 'info',
                                });

                                App.ui.notify('Indexing stopped');
                            });
                        });
                    },

                    getLog() {

                        this.$request(`/detektivo/idx/getRunnerLog/${this.index.name}`).then(res => {

                            if (!res || !res.log || !Array.isArray(res.log) || !res.log.length) {
                                this.isRunning = false;

                                this.log.push({
                                    time: this.time(),
                                    msg: 'Indexing finished',
                                    type: 'info',
                                });

                                App.ui.notify('Indexing finished');

                                return;
                            }

                            this.log = res.log;

                            setTimeout(() => {
                                this.getLog();
                            }, 1500);

                        }).catch(res => {
                            App.ui.notify((res && res.error) || 'Something went wrong', 'error');
                        });
                    },


                    // helper

                    time(timezone = 'UTC') {

                        const adjustedDate = new Date(new Intl.DateTimeFormat('en-US', {
                            dateStyle: 'short',
                            timeStyle: 'short',
                            timeZone: timezone,
                        }).format(new Date())+` ${timezone}`);

                        return Math.floor(adjustedDate.getTime() / 1000); // unixTimestamp
                    },

                    timeToDateTime(unixTimestamp, sourceTimezone = 'UTC', targetTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone) {

                        const sourceDate = new Date(unixTimestamp * 1000);
                        const formatOptions = {
                            hour12: false,
                            timeZone: targetTimezone,
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                        };

                        return sourceDate.toLocaleString(navigator.language || 'en-US', formatOptions);
                    }
                }
            }

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