<template>
    <div class="box border-solid no-margin no-padding no-border">
        <div class="box-header with-border">
            <h3 class="box-title">
                Line {{ index }}
                <small style="display: block">{{ index }} of {{ total }}</small>
            </h3>
            <div class="input-group pull-right import-preview-nav">
                <div class="input-group-btn">
                    <button class="btn btn-sm btn-default" @click.prevent="prev" :disabled="index <= 1">
                        <span class="fa-solid fa-chevron-left"></span>
                    </button>
                </div>
                <input ref="search" autocomplete="off" type="number" :min="1" :max="total" v-model="index" class="form-control input-sm" id="current-index" @focus="$event.target.select()" @keyup.left="prev" @keyup.right="next" />
                <div class="input-group-btn">
                    <button class="btn btn-sm btn-default" @click.prevent="next" :disabled="index >= total">
                        <span class="fa-solid fa-chevron-right"></span>
                    </button>
                </div>
            </div>
        </div>
        <div class="overlay" v-if="loading">
            <span class="fa-solid fa-refresh fa-spin"></span>
        </div>
        <div v-if="exception.length" class="box-body no-padding">
            <div class="alert alert-danger no-margin no-radius">
                <h4><i class="icon fa-solid fa-ban"></i> Exception</h4>
                <span v-html="exception"></span>
            </div>
        </div>
        <div v-if="errors.length" class="box-body no-padding">
            <div class="alert alert-warning no-margin no-radius">
                <h4><i class="icon fa-solid fa-exclamation-triangle"></i> Errors</h4>
                <ul v-for="error in errors">
                    <li v-html="error"></li>
                </ul>
            </div>
        </div>
        <div class="box-body no-margin">
            <div v-if="Object.keys(record).length" class="box-body no-margin no-padding">
                <dl class="dl-horizontal ig-list-horizontal" v-for="(value, field) in record">
                    <dt :title="field" class="ig-list-horizontal-label">{{ field.replace(/_/gi, ' ') }}</dt>
                    <dd v-if="canTable(value)">
                        <table class="table table-bordered table-condensed m-0" cellpadding="0" cellspacing="0">
                            <thead>
                            <tr class="active">
                                <th v-for="header in forTable(value).headers">
                                    {{ header }}
                                </th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="row in forTable(value).rows">
                                <td v-for="header in forTable(value).headers">
                                    {{ row[header] }}
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </dd>
                    <dd v-else-if="(typeof(value) === 'object' && value !== null && Object.keys.length)"><pre>{{ value }}</pre></dd>
                    <dd v-else>{{ value }}</dd>
                </dl>
            </div>
        </div>
    </div>
</template>

<script>
    import _ from "lodash";

    export default {
        props: {
            id: {type: Number, required: true},
            total: {type: Number, required: true}
        },
        data() {
            return {
                record: {},
                errors: [],
                exception: '',
                index: 1,
                loading: false,
                timeout: null
            }
        },
        watch: {
            index: function (newIndex, oldIndex) {
                if (newIndex > this.total || newIndex < 1) {
                    this.index = oldIndex;
                    return;
                }

                clearTimeout(this.timeout);
                this.timeout = setTimeout(function () {
                    this.request();
                    this.$refs.search.focus();
                }.bind(this), 1000);
            }
        },
        mounted() {
            this.request();
        },
        methods: {
            __(key) {
                if (window.Translation.hasOwnProperty(key)) {
                    return window.Translation[key];
                }
                return '';
            },
            prev() {
                if (this.index === 1) {
                    return;
                }

                this.index--;
            },
            next() {
                if (this.index >= this.total) {
                    return;
                }

                this.index++;
            },
            request() {
                this.$refs.search.blur();
                this.loading = true;
                axios.get('/admin/import/preview/' + this.id + '/' + this.index)
                    .then(response => {
                        this.record = response.data.record;
                        this.errors = response.data.errors;
                        this.exception = response.data.exception;
                        this.loading = false;
                    })
                    .catch(error => {
                        let errors = [];
                        if (
                          error.response.data.hasOwnProperty('message') &&
                          'unauthenticated.' === error.response.data.message.toLowerCase()
                        ) {
                          errors.push("Your session has timed out. Please refresh the page to sign in again.");
                        } else {
                          errors = error.response.data;
                        }

                        this.errors = errors;
                        this.loading = false;
                    });
            },
            canTable(value) {
              return _.isArray(value) && value.length;
            },
            forTable(value) {
                if (value.length <= 0) {
                  return value;
                }

                return {
                    headers: Object.keys(_.first(value)),
                    rows: value
                }
            }
        }
    }
</script>
