<template lang="pug">
    .customer-searcher
        input(type="text" placeholder="Buscar un cliente" v-model="search")
</template>

<script>
    import Fuse from 'fuse.js'
    import { mapGetters, mapActions } from 'vuex'

    export default {
        computed: mapGetters([
            'customers'
        ]),
        methods: {
            initFuse() {
                if (this.fuse) {
                    this.fuse.setCollection(this.customers)
                    return
                }

                this.fuse = new Fuse(this.customers, {
                    shouldSort: true,
                    threshold: 0.4,
                    location: 0,
                    distance: 100,
                    maxPatternLength: 32,
                    minMatchCharLength: 1,
                    keys: [
                        'name',
                        'phone',
                        'mobile',
                        'email',
                        'categories.name'
                    ]
                })
            },
            fuzzySearch() {
                this.results = this.fuse.search(this.search)
            },
            ...mapActions([
                'filterCustomers'
            ])
        },
        watch: {
            customers() {
                this.initFuse()
            },
            search() {
                this.fuzzySearch()
            },
            results() {
                this.filterCustomers(this.results)
            }
        },
        data() {
            return {
                search: '',
                fuse: null,
                results: []
            }
        }
    }
</script>
<style lang="sass">
    .customer-searcher
        width: 100%
        height: 35px

        input
            width: 100%
            height: inherit
            text-align: center
            border-radius: 0
            font:
                size: 11pt
                style: normal
                weight: bold
</style>
