<template>
    <div>
        <h1>{{ toDoList.data.attributes.data.name }}</h1>
        <ul class="draggable-list">
            <div v-if="toDoList.data.attributes.data.to_dos.to_dos_count < 1">
                ------- no to Do -------
            </div>
            <li v-else v-for="(toDo, index) in toDoList.data.attributes.data.to_dos.data" draggable="true">
                <span>=</span>
                {{ toDo.data.attributes.data.name }}
                <input type="checkbox" name="do" id="do">
                <span @click="deleteToDo(toDo, index)">X</span>
            </li>
        </ul>
        <div>
            <InputField name="name" classes="inline" placeholder="New To Do" required @update:field="name = $event" :errors="errors" />
            <button class="btn-primary" @click="addToDo">ADD</button>
        </div>
    </div>
</template>

<script>
    import InputField from "../../components/InputField";

    export default {
        name: "ToDoList",
        components: {
            InputField
        },
        data: function () {
            return {
                name: '',
                errors: null,
                list: null,
            }
        },
        props: {
            toDoList: {
                type: Object,
                require: true
            }
        },
        mounted() {
            this.list = this.$el.querySelector('.draggable-list')
            console.log(this.list)
        },
        methods: {
            addToDo: function () {
                axios.post('/api/to-do-lists/' + this.toDoList.data.to_do_list_id + '/to-do', {name: this.name})
                    .then(res => {
                        this.toDoList.data.attributes.data.to_dos.data.push(res.data)
                        this.name = ''
                    })
                    .catch(errorRes => {
                        console.log('Internal Error, Unable to delete contact.' + errorRes)
                    })
            },
            deleteToDo: function (toDo, position) {
                axios.delete('/api/to-do-lists/' + this.toDoList.data.to_do_list_id + '/to-do/' + toDo.data.to_do_id)
                    .then(res => {
                        this.toDoList.data.attributes.data.to_dos.data.splice(position, 1)
                    })
                    .catch(errorRes => {
                        console.log('Internal Error, Unable to delete contact.' + errorRes)
                    })
            }
        }
    }
</script>
