<template>
    <div id="searchers-create">
        <div>
            <h1> {{ searcher.id ? 'Edit' : 'New' }} searcher </h1>

            <InputText v-model="name"
                   type="text"
                   placeholder="Enter searcher name"
                   class="input">
            </InputText>

            <Button @click="onSave" :disabled=" ! name || rows.length === 0">
                Save
            </Button>
        </div>

        <div v-if="standalone">
            <p>
                A searcher may contain multiple compounded searchers on multiple rows and columns.
            </p>

            <p>
                Each searcher in a row is extending the searching criteria on the content resulted from the
                previous row searchers.
            </p>
        </div>

        <div v-for="(row, rowIndex) in rows"
             :key="`row-${rowIndex}`"
             class="searchers-row flex-row">
            <div v-for="(searcher, columnIndex) in row"
                 :key="`column-${columnIndex}`"
                 class="searcher box">
                <searcher-show :searcher="searcher"
                               :editable="true"
                               :standalone="false"
                               @deleted="onRemoveItem(rowIndex, columnIndex)">
                </searcher-show>
            </div>

            <add-box :ignore-searcher-ids="searcher.id ? [searcher.id] : []"
                     @added="(searcher) => { onSearcherAdded(searcher, rowIndex); }">
            </add-box>
        </div>

        <div class="searchers-row flex-row">
            <add-box @added="onNewRowSearcherAdded">
            </add-box>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Prop, Vue} from "vue-property-decorator";
    import AddBox from './AddBox.vue';
    import SearcherShow from './Show.vue';

    @Component({
        name: 'SearcherCreate',

        components: {
            AddBox,
            SearcherShow,
        },
    })
    export default class Create extends Vue {
        private id: String = '';
        private name: String = '';
        private rows: Array<Array<any>> = [];

        @Prop({
            default: () => {
                return {
                    id: '',
                    name: '',
                    rows: [],
                };
            }
        })
        public readonly searcher!: any;

        @Prop({default: true})
        public readonly standalone!: boolean;

        onNewRowSearcherAdded(searcher: Object) {
            const length = this.rows.push([]);

            this.onSearcherAdded(searcher, length - 1);
        }

        async onSearcherAdded(searcher: any, rowIndex: number) {
            try {
                const { data } = await (window as any).axios.get(`/searchers/${searcher.id}`);

                this.rows[rowIndex].push(data.searcher);
            } catch (e) {

            }
        }

        onSave() {
            if (this.standalone) {
                this.save();

                return;
            }

            const updatedSearcher = Object.assign(this.searcher, {
                name: this.name,
                rows: this.rows,
            });

            this.$emit('updated', updatedSearcher);
        }

        async save() {
            try {
                const searcher = this.id ? await this.update() : await this.create();

                window.location.href = `/searchers/${searcher.id}`;
            } catch (e) {
                console.log(e);
                console.log('Something went wrong.');
            }
        }

        async update() {
            const { data } = await (window as any).axios.put(`/searchers/${this.id}`, {
                name: this.name,
                rows: this.rows,
            });

            return data.searcher;
        }

        async create() {
            const { data } = await (window as any).axios.post('/searchers', {
                name: this.name,
                rows: this.rows,
            });

            return data.searcher;
        }

        onRemoveItem(rowIndex: number, columnIndex: number) {
            if (
                this.rows[rowIndex][columnIndex].hasOwnProperty('rows') &&
                this.rows[rowIndex][columnIndex].rows.length === 0
            ) {
                this.$toast.add({
                    severity: 'info',
                    summary: `${this.searcher.name} searcher deleted`,
                    detail: 'The searcher has been deleted as well because it does not have any searching data..',
                    life: 4000,
                });
            }

            this.rows[rowIndex].splice(columnIndex, 1);

            if (this.rows[rowIndex].length === 0) {
                this.rows.splice(rowIndex, 1);
            }
        }

        created() {
            // Editing.
            if (this.searcher.id) {
                this.id = this.searcher.id;
                this.rows = this.searcher.rows;
                this.name = this.searcher.name;
            }
        }
    };
</script>
