<template>
    <div>
        <h1> Searchers </h1>

        <div v-if=" ! allowSelect" style="margin-bottom: 1rem;">
            <a href="/searchers/create">
                <Button class="fc-button p-button-success">
                    Add searcher
                </Button>
            </a>
        </div>

        <div class="content">
            <DataTable
                :value.sync="searchers"
                :selection.sync="selectedSearcher"
                dataKey="id"
                :selectionMode="allowSelect ? 'single' : ''"
                class="p-datatable-md"
                :paginator="true"
                :rows="10"
                paginatorTemplate="CurrentPageReport FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
                currentPageReportTemplate="Showing {first} to {last} of {totalRecords}"
                :rowsPerPageOptions="[10,20,50]">

                <Column v-if="allowSelect" selectionMode="single" headerStyle="width: 3em"></Column>

                <Column header="Name" sortable>
                    <template #body="slotProps">
                        <a @click.stop="onOpen(slotProps.data.id)" class="searcher-link">
                            {{ slotProps.data.name }}
                        </a>
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>
</template>

<script lang="ts">
import {Component, Prop, Vue, Watch} from "vue-property-decorator";
import {Searcher} from "@/interfaces/Searcher";

@Component({
})
export default class Index extends Vue {
    private searchers: Array<Searcher> = [];
    private selectedSearcher: any = {};

    @Prop({default: false})
    public readonly allowSelect!: boolean;

    @Prop({default: () => []})
    public readonly ignoreSearcherIds!: Array<string>;

    async boot() {
        try {
            const { data } = await (window as any).axios.get('/searchers');

            this.searchers = data.searchers.filter((searcher: Searcher) => {
                return ! this.ignoreSearcherIds.includes(searcher.id);
            });
        } catch (e) {

        }
    }

    onOpen(id: string) {
        window.open(this.getURL(id), '_blank');
    }

    getURL(id: string) {
        return `/searchers/${id}`;
    }

    @Watch('selectedSearcher')
    selectedSearcherIdChanged(value: any) {
        this.$emit('selected', value);
    }

    created() {
        this.boot();
    }
};
</script>
