class View {
	charLimit = 70;

	constructor() {
		this.form   = document.querySelector("#add_form")
		this.input  = document.querySelector("#input_todo")
		this.list   = document.querySelector("#todos_list")
		this.tabs   = document.querySelectorAll("#add_form span a")
		this.loader = document.querySelector("#loader")
		this.count = document.querySelector("#count")
		
		
		this.input.addEventListener("input", (e) => {
			if (e.target.value.length >= this.charLimit) {
				e.target.value = e.target.value.substring(0,this.charLimit);
			}
			count.textContent = e.target.value.length;
		});
		count.nextSibling.textContent = `/${this.charLimit} characters`
	}

	#getTodo() {
		return this.input.value
	}

	#resetInput() {
		this.input.value = ''
		count.textContent = 0
	}

	#createNewTodoElement(todo){
		let li = document.createElement("li")
		li.classList.add("todo");
		li.dataset.id = todo.id;

		let label = document.createElement("label");

		let checkbox = document.createElement("input");
		
		checkbox.type = "checkbox";
		checkbox.checked = todo.done;

		let span = document.createElement("span");

		span.textContent = todo.text;

		let trash = document.createElement("i");
		trash.classList.add("fas","fa-trash");
		label.append(checkbox, span);
		label.append(label, trash);
		return li
	}


	setFilterTabs(filter){
		this.tabs.forEach( tab => {
			if (filter === tab.id)		
				tab.classList.add("is-active")
			else 
				tab.classList.remove("is-active")
		})
	}

	renderTodoList(todos) {
		let list = new DocumentFragment()
		for (let todo of todos){
			list.appendChild(this.#createNewTodoElement(todo))
		}
		this.list.replaceChildren(list)
	}




	/** Abonnements événements **/

	bindAddTodo(handler) {
		this.form.addEventListener("submit", (e=>{
			e.preventDefault()
			let text = this.#getTodo()
			handler(text)
			this.#resetInput()
		}))
	}


	bindDeleteTodo(handler) {
	this.list.addEventListener("click", (e=>{
	if (!e.target.classList.contains("fa-trash")) {
    return;
	} else {
		let li = e.target.closest(".todo") 
		let id = li.dataset.id;
		handler(id);

		})

	}

	bindEditTodo(handler) {
		// TODO
	}

	bindToggleTodo(handler) {
		this.list.addEventListener("change", (e=>{
	if (e.target.type !== "checkbox") {
	return;
	}else {
		let li = e.target.closest(".todo") 
		let id = li.dataset.id;
		handler(id);

		})
	
}
