<template>
	<md-table v-model="searched" md-card md-sort="id" md-sort-order="asc">
		<md-table-toolbar>
			<h1 class="md-title md-toolbar-section-start">{{ currentUser.name }}'s anime</h1>
			<div class="md-toolbar-section-end">
				<md-field md-clearable>
					<md-input placeholder="Search by name..." v-model="search" @input="searchOnTable" />
				</md-field>
				<md-button 
					class="md-icon-button md-primary"
					@click="refresh"
				>
					<md-icon>refresh</md-icon>
				</md-button>
			</div>
		</md-table-toolbar>

		<md-table-empty-state v-if="loading">
			<md-progress-spinner class="md-accent" md-mode="indeterminate"></md-progress-spinner>
		</md-table-empty-state>
		<md-table-empty-state 
			v-else
			md-label="No results"
			md-description="It's a void"
		/>

		<md-table-row slot="md-table-row" slot-scope="{ item }">
			<md-table-cell md-label="#" md-numeric md-sort-by="anime.id">{{ item.anime.id }}</md-table-cell>
			<md-table-cell md-label="Title" md-sort-by="anime.title">{{ item.anime.title }}</md-table-cell>
		</md-table-row>
	</md-table>
</template>

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

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

@Component({})
export default class Home extends Vue {
	public loading: boolean = false

	public search: string = ''
	public searched: Meikan.UserAnime[] = []

	@user.Getter
	private currentUser!: Meikan.User

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

	@userAnime.Action
	private fetchUserAnime!: (user: Meikan.User) => Promise<Meikan.UserAnime[]>

	@userAnime.Getter
	private anime!: Meikan.UserAnime[]

	private created() {
		if (this.anime.length !== 0) {
			this.searched = this.anime
			return
		}
		this.loading = true
		this.fetchUserAnime(this.currentUser)
			.then(() => {
				this.loading = false
				this.searched = this.anime
			})
	}

	private refresh() {
		this.resetUserAnime()

		this.loading = true
		this.fetchUserAnime(this.currentUser)
			.then(() => {
				this.loading = false
			})
	}

	private searchOnTable() {
		if (this.search.length === 0) {
			this.searched = this.anime
		}

		this.searched = this.anime.filter((item) => {
			return item.anime.title
				.toLowerCase()
				.includes(this.search.toLowerCase())
		})
	}
}
</script>
