<template>
	<multiselect
		class="control is-expanded"
		v-focus
		:loading="listSerivce.loading"
		:placeholder="$t('list.search')"
		@search="findLists"
		:search-results="foundLists"
		@select="select"
		label="title"
		v-model="list"
		:select-placeholder="$t('list.searchSelect')"
	>
		<template v-slot:searchResult="props">
			<span class="list-namespace-title">{{ namespace(props.option.namespaceId) }} ></span>
			{{ props.option.title }}
		</template>
	</multiselect>
</template>

<script>
import ListService from '../../../services/list'
import Multiselect from '@/components/input/multiselect'

export default {
	name: 'listSearch',
	data() {
		return {
			listSerivce: ListService,
			foundLists: [],
		}
	},
	components: {
		Multiselect,
	},
	prop: ['list'],
	model: {
		prop: 'list',
		event: 'selected',
	},
	beforeMount() {
		this.listService = new ListService()
	},
	methods: {
		findLists(query) {
			if (query === '') {
				this.clearAll()
				return
			}

			this.listService.getAll({}, {s: query})
				.then(response => {
					this.$set(this, 'foundLists', response)
					this.$set(this, 'list', response)
				})
				.catch(e => {
					this.error(e)
				})
		},
		clearAll() {
			this.$set(this, 'foundLists', [])
		},
		select(list) {
			this.$emit('selected', list)
		},
		namespace(namespaceId) {
			const namespace = this.$store.getters['namespaces/getNamespaceById'](namespaceId)
			if (namespace !== null) {
				return namespace.title
			}
			return this.$t('list.shared')
		},
		handleInput (value) {
			this.$emit('selected', value)
		},		
	},
}
</script>
