<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 class="kiss-flex kiss-flex-middle kiss-margin-xsmall-top">
                            <span class="kiss-badge kiss-margin-small-end" :class="runnerStatusBadgeClass()">{{ runnerStatusLabel() }}</span>
                            <span class="kiss-text-caption kiss-color-muted kiss-text-monospace kiss-text-truncate" style="max-width:320px;" v-if="runnerState && runnerState.processId" :title="runnerState.processId">
                                PID {{ runnerState.processId }}
                            </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="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 class="kiss-text-center">
                        <app-loader class="kiss-display-inline-block" mode="dots"></app-loader>
                        <p class="kiss-size-large kiss-margin-small-top">{{ runnerState && runnerState.status === 'queued' ? '<?=t('Indexing queued')?>' : '<?=t('Indexing in progress')?>' }}</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 log">
                        <div class="kiss-text-bold kiss-color-muted kiss-margin-end" style="width:200px;">&mdash; {{ timeToDateTime(entry.time) }}</div>
                        <div class="kiss-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: [],
                        runnerState: <?=json_encode($runnerState ?? null) ?>,
                        lastStatus: <?=json_encode($runnerState['status'] ?? null) ?>,
                    }
                },

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

                methods: {

                    start() {

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

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

                            if (!res || res.success === false) {
                                this.isRunning = false;
                                App.ui.notify((res && res.error) || 'Something went wrong', 'error');
                                return;
                            }

                            this.runnerState = (res && res.state) || null;
                            this.lastStatus = this.runnerState ? this.runnerState.status : null;

                            this.getLog();

                        }).catch(res => {
                            this.isRunning = false;
                            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 => {

                                if (!res || res.success === false) {
                                    App.ui.notify((res && res.error) || 'Something went wrong', 'error');
                                    return;
                                }

                                this.runnerState = (res && res.state) || this.runnerState;
                                this.isRunning = false;
                                this.getLog();
                            }).catch(res => {
                                App.ui.notify((res && res.error) || 'Something went wrong', 'error');
                            });
                        });
                    },

                    getLog() {

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

                            const entries = (res && Array.isArray(res.log)) ? res.log : [];
                            const fallbackTime = (res && Number.isInteger(res.serverTime)) ? res.serverTime : Math.floor(Date.now() / 1000);
                            const state = (res && res.state && typeof res.state === 'object')
                                ? res.state
                                : {status: 'idle', time: fallbackTime};
                            const status = state.status || 'idle';
                            const previousStatus = this.lastStatus;

                            this.log = entries;
                            this.runnerState = state;
                            this.lastStatus = status;
                            this.isRunning = status === 'queued' || status === 'running';

                            if (previousStatus && previousStatus !== status) {
                                if (status === 'finished') {
                                    App.ui.notify('Indexing finished');
                                } else if (status === 'stopped') {
                                    App.ui.notify('Indexing stopped');
                                } else if (status === 'failed') {
                                    App.ui.notify(state.error ? `Indexing failed: ${state.error}` : 'Indexing failed', 'error');
                                }
                            }

                            if (!this.isRunning) {
                                return;
                            }

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

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


                    // helper

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

                        if (!unixTimestamp) {
                            return '';
                        }

                        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);
                    },

                    runnerStatusLabel() {

                        const status = (this.runnerState && this.runnerState.status) ? this.runnerState.status : 'idle';

                        return {
                            idle: 'Idle',
                            queued: 'Queued',
                            running: 'Running',
                            finished: 'Finished',
                            stopped: 'Stopped',
                            failed: 'Failed',
                        }[status] || status;
                    },

                    runnerStatusBadgeClass() {

                        const status = (this.runnerState && this.runnerState.status) ? this.runnerState.status : 'idle';

                        return {
                            idle: 'kiss-badge-muted',
                            queued: 'kiss-badge-warning',
                            running: 'kiss-badge-primary',
                            finished: 'kiss-badge-success',
                            stopped: 'kiss-badge-danger',
                            failed: 'kiss-badge-danger',
                        }[status] || 'kiss-badge-muted';
                    },
                }
            }

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