<template>
	<div>
		<md-table v-model="foundUsers" @md-selected="onSelect">
			<md-table-toolbar>
				<div class="md-toolbar-section-start">
					<h1 class="md-title">Users</h1>
				</div>

				<md-field md-clearable class="md-toolbar-section-end">
					<md-input placeholder="Search users" @input="onInput" />
				</md-field>
			</md-table-toolbar>

			<md-table-row slot="md-table-row" slot-scope="{ item }" md-selectable="single">
				<md-table-cell md-label="#" md-numeric width="100">{{ item.id }}</md-table-cell>
				<md-table-cell md-label="Title" md-sort-by="title">{{ item.name }}</md-table-cell>
			</md-table-row>
		</md-table>
	</div>
</template>

<script lang="ts">
import _ from 'lodash'
import { Component, Vue } from 'vue-property-decorator'
import { namespace } from 'vuex-class'

const userStore = namespace('user')
const userAnimeStore = namespace('userAnime')

@Component({})
export default class Home extends Vue {
	@userStore.Mutation('setCurrentUser')
	private setCurrentUser!: (user: User) => void

	@userStore.Action('findUsers')
	private findUsers!: (name: string) => Promise<User[]>

	@userStore.Action('resetFoundUsers')
	private resetFoundUsers!: () => void

	@userStore.Getter('foundUsers')
	private foundUsers!: User[]

	@userAnimeStore.Action
	private resetUserAnime!: () => void

	private onInput = _.debounce((name: string) => {
		if (name === '') {
			this.resetFoundUsers()
			return
		}

		this.findUsers(name)
	}, 200)

	private onSelect(user: User) {
		this.setCurrentUser(user)
		this.resetUserAnime()

		this.$router.push({ name: 'userAnime' })
	}
}
</script>
