/** @odoo-module **/

import { Component, useState } from "@odoo/owl";
import { TodoItem } from "./todo_item";
import "../utils.js";
import { useAutofocus } from "../utils.js";

export class TodoList extends Component {
    static template = "awesome_owl.todo_list";
    static components = { TodoItem };

    setup() {
        this.todoCounter = 1;
        this.todos = useState([]);
        useAutofocus('todo_input');
    }

    addTodo(ev) {
        // If the key was enter and input isn't empty
        if(ev.keyCode === 13) {
            if(ev.target.value !== '') {
                // Let's create a todo
                this.todos.push({ id: this.todoCounter++, description: ev.target.value, isCompleted: false });
                ev.target.value = '';
            }
        }
    }

    toggleState(id) {
        const todo = this.todos.find((obj) => obj.id === id);
        if (todo) {
            todo.isCompleted = !todo.isCompleted;
        }
    }

    removeItem(id) {
        const todoIndex = this.todos.findIndex((obj) => obj.id === id);
        if (todoIndex >= 0) {
            this.todos.splice(todoIndex, 1);
        }
    }
}