<app>
<router base = {base}>
<route path="/:filter?"
	   on-before-mount = { changeFilter }
	   on-before-update = { changeFilter }
	   > 

	   <h1>To Do List</h1>

	   <todo-form
		 add = { add } />

		<todo-nav 
	     selection = {state.filter} 
	     left = {this.state.todos.filter(todo => !todo.done).length} />

	    <todo-list 
	      todos = { filterTodos() } 
	      toggle = { toggle }
	      remove = { remove  } />

</route>
</router>
<script>
	export default {
		base : '/~denis/web_2024/tp5/todo-riot/', // Votre URL
		state : {
			todos : [],
			filter : 'all'
		},
		changeFilter(r){
			this.state.filter = r.params.filter || 'all'
		},

		async onBeforeMount(props, state) {
			let todos = await this.serviceData.getTodos()
			this.state.todos = todos;
			this.update()
		},
		filterTodos(){

			if (this.state.filter === 'all')
				return this.state.todos

			if (this.state.filter === 'active')
				return this.state.todos.filter(e=> !e.done)

			if (this.state.filter === 'done')
				return this.state.todos.filter(e=> e.done)
		},
		async remove(e,todo){
			e.preventDefault()
			let res = await this.serviceData.removeTodo(todo)
			let todos = await this.serviceData.getTodos()
			this.state.todos = todos
			this.update()
		},

		async add(text) {
			let res = await this.serviceData.addTodo({title : text , done : false})
			let todos = await this.serviceData.getTodos()
			this.state.todos = todos
			this.update()
		},

		async toggle(todo) {
			let res = await this.serviceData.toggleTodo(todo);
			let todos = await this.serviceData.getTodos()
			this.state.todos = todos
			this.update()
		}
	}
</script>
</app>
