<template>
    <div id="searchers-create">
        <div>
            <input v-model="name"
                   type="text"
                   placeholder="Enter searcher name"
                   class="input">

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

        <div v-for="(row, rowIndex) in rows" :key="`row-${rowIndex}`" class="flex-row">
            <div v-for="(searcher, columnIndex) in row" :key="`column-${columnIndex}`">
                <div class="box">
                    {{ searcher.name }}
                </div>
            </div>

            <add-box @added="(searcher) => { onSearcherAdded(searcher, rowIndex); }">
            </add-box>
        </div>

        <add-box @added="onNewRowSearcherAdded">
        </add-box>
    </div>
</template>

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

    @Component({
        components: {
            AddBox,
        },
    })
    export default class Create extends Vue {
        private name: String = '';
        private rows: Array<Array<Object>> = [];

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

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

        onSearcherAdded(searcher: Object, rowIndex: number) {
            this.rows[rowIndex].push(searcher);
        }

        async onSave() {
            try {
                const { data } = await (window as any).axios.post('/searchers', {
                    name: this.name,
                    rows: this.rows,
                });
            } catch (e) {
                console.log(e);
                console.log('Something went wrong.');
            }
        }
    };
</script>
