<template>
    <div>
        <div class="m-2 px-2 pt-2 bg-orange-400 rounded flex flex-col justify-between shadow">
            <div>
                <h1 class="text-2xl font-bold mb-2">{{ 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>
                    <ToDo v-else
                          v-for="(toDo, indexToDo) in toDoList.data.attributes.data.to_dos.data"
                          :key="indexToDo"
                          :toDo="toDo"
                          :position="indexToDo" />
                </ul>
            </div>
            <div class="flex items-center mt-2">
                <InputField name="name" classes="py-1" placeholder="New To Do" required @update:field="name = $event" :errors="errors" />
                <button class="btn-primary ml-1 mb-2 py-1" @click="addToDo">ADD</button>
            </div>
        </div>
    </div>
</template>

<script>
import InputField from '../../components/InputField'
import ToDo from './ToDo'

export default {
    name: 'ToDoList',
    components: {
        InputField, ToDo
    },
    data: function () {
        return {
            name: '',
            errors: null,
            list: null,
            edit: false,
        }
    },
    props: {
        toDoList: {
            type: Object,
            require: true
        }
    },
    mounted() {
        this.list = this.$el.querySelector('.draggable-list')
        console.log(this.list)
    },
    methods: {
        addToDo: function () {
            // eslint-disable-next-line no-undef
            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) {
            // eslint-disable-next-line no-undef
            axios.delete('/api/to-do-lists/' + this.toDoList.data.to_do_list_id + '/to-do/' + toDo.data.to_do_id)
                .then(() => {
                    this.toDoList.data.attributes.data.to_dos.data.splice(position, 1)
                })
                .catch(errorRes => {
                    console.log('Internal Error, Unable to delete contact.' + errorRes)
                })
        }
    }
}
</script>


