<template lang="pug">

div#modal-container
//- div   {{employees}}

//- TODO: #2 Can't highlight list-group-item when hovering
//- TODO: #3 Close Modal after successful input
<!-- Schedule Table -->
table(class='table table-bordered table-sm' v-for="(row, rIndex) in scheduleData" :key="rIndex")
    thead
        tr
            td(style="width: 100px" class="fw-bold") {{ format(startDate, "MMMM", {locale: de}) }}
            td(v-for="(day, index) in weekdays" :key="index"  :class="{'text-body text-opacity-50 bg-secondary bg-opacity-10' : row.dates[index] === null}") {{ day }}
        tr
            td.fw-bold {{ format(startDate, "y") }}
            td(v-for="(date, dIndex) in row.dates" :key="dIndex"  :class="{'bg-secondary bg-opacity-10' : row.dates[dIndex] === null}") 
                template(v-if="date !== null") {{ format(date, "dd.MM.")}}
    tbody 
        tr(v-for="(employee, eIndex) in row.employees" :key="eIndex")
            td {{employee.handle}} 
                button.btn.btn-outline-secondary.btn-sm(
                    @click="removeEmployee(rIndex, employee)"
                ) 
                    i.bi.bi-trash
            td(v-for="(date, dIndex) in row.dates" :key="dIndex" :class="{'bg-secondary bg-opacity-10' : row.dates[dIndex] === null}") &nbsp;
        tr()
            td(style="width: 250px")
                button(
                        class="btn btn-outline-secondary btn-sm" 
                        @click="onClickOpenModal(rIndex)"
                    )
                    i.bi.bi-plus-lg
            td(v-for="(date, dIndex) in row.dates" :key="dIndex" :class="{'bg-secondary bg-opacity-10' : row.dates[dIndex] === null}") &nbsp;


</template>


<script setup lang="ts">
    import { toRef, computed, ref, h, render } from 'vue'
    import { storeToRefs } from 'pinia'
    import { useEmployees } from '/src/stores/employees.js'
    import { addMonths, subDays, addDays, format, getISODay, isValid, eachDayOfInterval } from 'date-fns'
    import { de } from 'date-fns/locale'
    import AddEmployeeModal from './AddEmployeeModal.vue'

    /*
    *   Props / Refs
    */
    const props = defineProps<{
        startDate: Date,
        initialOffset: number
    }>()
    const addEmployeeRow = ref()
    const addEmployeeInput = ref('')
    const autocomplete = ref(null)

    const startDate = toRef(props, 'startDate')
    const endDate = computed(():Date => subDays(addMonths(startDate.value, 1), 1))

    /*
    *   Local variables
    */
    const weekdays : string[] = getDoubleWeekdays()
    const store = useEmployees()
    const { employees } = storeToRefs(store)
    
    const offset = computed(() => getISODay(startDate.value) - 1 + props.initialOffset)
    
    // TODO: #4 Make scheduleData writable, only rewrite dates when startDate, endDate and offset change, keep employees?
    const scheduleData = computed( () => {
        let arr : ScheduleData = []
        let row : ScheduleRow = {dates: [], employees: []}

        let start = startDate.value
        let end = endDate.value
        let i

        for (i = 0; i < offset.value ; i++) {
            row.dates.push(null)
        }

        while (start <= end){
            while (i < 14 && start <= end){
                row.dates.push(start)
                start = addDays(start, 1)
                i++
            }
            while (i < 14) {
                row.dates.push(null)
                i++
            }
            arr.push(row)
            row = {dates: [], employees: []}
            i = 0
        }

        return arr
    })

    function getDoubleWeekdays() : string[] {
        let arr = ['Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.', 'So.']
        return arr.concat(arr)
    }

    function removeEmployee(rIndex: number, emp : Employee) : void {
        let i = scheduleData.value[rIndex].employees.indexOf(emp)
        if(i > -1){
            scheduleData.value[rIndex].employees.splice(i, 1)
        }
    }


    /**
     * TODO: #1 Can't focus the autocomplete input 
     */
    function onClickOpenModal(index: number): void {
        const modal = h('AddEmployeeModal', {
            searchData: employees.value,
            searchFields: ['name'],
            sourceRow: index
        })
        render(modal, ,)
    }

    function addEmployee(param : Employee){
        console.log(addEmployeeRow.value)
        console.log(param)

        if (addEmployeeRow.value !== undefined && param !== null) {
            scheduleData.value[addEmployeeRow.value].employees.push(param)
            addEmployeeRow.value = undefined
            addEmployeeInput.value = ''
        }
        console.log(scheduleData.value)
    }

</script>

<style scoped>
    table {
        table-layout: fixed
    }

    .o-acp__item.list-group-item:hover {
        background-color: aliceblue !important;
    }

</style>