<template>
    <section v-if="!addBool"
        :class="['template-checklist-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'label-darkmode' : 'label-lightmode']">Checklist:</div>
        <table class="data-table" id="template-checklist">
            <tbody>
                <tr :class="['table-row', darkMode ? 'tr-head-darkmode' : 'tr-head-lightmode']" id="table-head">
                    <th
                        :class="['Step', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        Step</th>
                    <th
                        :class="['Asset', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        Asset</th>
                    <th
                        :class="['Task', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        Task</th>
                    <th :class="['Comments', darkMode ? 'th-darkmode' : 'th-lightmode']">Comments</th>
                </tr>
                <tr v-for="todo in mvtTodos" :key="todo.primaryID"
                    :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                    <td
                        :class="['Step', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        {{ todo.rowID }}
                    </td>
                    <td v-if="!editable"
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        {{ todo.asset }}</td>
                    <td v-if="editable"
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        <select id="customersDropDownChosenCI" v-model="todo.asset" @change="updateMVTTodo(todo)"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="ci in configItemList" :key="ci.primaryID">
                                {{ ci.assetName }}
                            </option>
                        </select>
                    </td>
                    <td v-if="!editable"
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        {{ todo.task }}</td>
                    <td v-if="editable"
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        <input type="text" v-model="todo.task" @change="updateMVTTodo(todo)"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </td>
                    <td v-if="!editable" :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"> {{ todo.commets
                    }}</td>
                    <td v-if="editable" :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"> <input type="text"
                            v-model="todo.commets" @change="updateMVTTodo(todo)"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']"> <button
                            :class="[darkMode ? 'deleteMvtTodos-darkmode' : 'deleteMvtTodos-lightmode']"
                            @click="deleteMVTTodo(todo.primaryID)">-</button>
                    </td>
                </tr>
                <tr v-if="editable && addRow" :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                    <td
                        :class="['Step', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        {{ newStepTodo }}
                    </td>
                    <td
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        <select id="customersDropDownChosenCI" v-model="newAssetTodo"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="ci in configItemList" :key="ci.primaryID">
                                {{ ci.assetName }}
                            </option>
                        </select>
                    </td>
                    <td
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        <input type="text" v-model="newTaskTodo"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </td>
                    <td :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"><input type="text"
                            v-model="newCommentsTodo"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']"> <button
                            :class="[darkMode ? 'saveMvtTodos-darkmode' : 'saveMvtTodos-lightmode']"
                            @click="addMVTTodo()">Save</button> <button
                            :class="[darkMode ? 'deleteLastMvtTodos-darkmode' : 'deleteLastMvtTodos-lightmode']"
                            @click="deleteNewRow()">-</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </section>
    <section v-if="editable && !addBool" id="editMvtTodos">
        <button :class="[darkMode ? 'editMvtTodos-darkmode' : 'editMvtTodos-lightmode']"
            @click="addChecklistRow()">+</button>
    </section>
    <section v-if="addBool"
        :class="['template-checklist-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'label-darkmode' : 'label-lightmode']">Checklist:</div>
        <table class="data-table" id="template-checklist">
            <tbody>
                <tr :class="['table-row', darkMode ? 'tr-head-darkmode' : 'tr-head-lightmode']" id="table-head">
                    <th
                        :class="['Step', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        Step</th>
                    <th
                        :class="['Asset', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        Asset</th>
                    <th
                        :class="['Task', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        Task</th>
                    <th :class="['Comments', darkMode ? 'th-darkmode' : 'th-lightmode']">Comments</th>
                </tr>
                <tr v-for="(newT, index) in newTodos" :key="index"
                    :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                    <td
                        :class="['Step', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        {{ newT.rowID }}
                    </td>
                    <td
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        <select id="customersDropDownChosenCI" v-model="newT.asset"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="ci in configItemList" :key="ci.primaryID">
                                {{ ci.assetName }}
                            </option>
                        </select>
                    </td>
                    <td
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        <input type="text" v-model="newT.task"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </td>
                    <td :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"> <input type="text"
                            v-model="newT.comments"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']"> <button
                            :class="[darkMode ? 'deleteMvtTodos-darkmode' : 'deleteLastMvtTodos-lightmode']"
                            @click="deleteMVTTodoFromNewTodos(index)">-</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </section>
    <section v-if="addBool" id="editMvtTodos">
        <button :class="[darkMode ? 'editMvtTodos-darkmode' : 'editMvtTodos-lightmode']"
            @click="addRowForNewMVT()">+</button>
    </section>
    <section v-if="addBool" id="saveNewMVT">
        <button :class="[darkMode ? 'saveNewMVT-darkmode' : 'saveNewMVT-lightmode']" @click="addMVT()">Save</button>
    </section>
</template>
  

<script setup>
import { ref, onMounted, watch } from 'vue';
import Axios from '../axios.config.js';
import clientsideConfig from '../../clientsideConfig.js';
import { useStore } from 'vuex';
import { computed } from 'vue';

const store = useStore();
const addBool = computed(() => store.state.new);
const editable = computed(() => store.state.editable);

const newNameMVT = computed(() => store.state.newNameMVT);
const newCustomerIDMVT = computed(() => store.state.newCustomerIDMVT);
const newCustomerMVT = computed(() => store.state.newCustomerMVT);
const newLastViewMVT = computed(() => store.state.newLastViewMVT);
const newUserMVT = computed(() => store.state.newUserMVT);
const newTypeMVT = computed(() => store.state.newTypeMVT);
const newNotesMVT = computed(() => store.state.newNotesMVT);
const newStepTodo = computed(() => mvtTodos.value.length);
const chosenMVTId = computed(() => store.state.chosenMVTId);
const clientChanged = computed(() => store.state.clientChanged);
const changedClientId = computed(() => store.state.changedClientId);

const darkMode = ref(true)
const addRow = ref(false);
const configItemList = ref([]);
const maintenanceVisitTemplates = ref([]);
const mvtTodos = ref([])
const MVT = ref({})
const newAssetTodo = ref('');
const newTaskTodo = ref('');
const newCommentsTodo = ref('');
const newTodos = reactive([]);
const newRowId = computed(() => newTodos.length)

// delete new todo row
const deleteNewRow = () => {
    newAssetTodo.value = '';
    newTaskTodo.value = '';
    newCommentsTodo.value = '';
    addRow.value = false;
}

const deleteMVTTodoFromNewTodos = (index) => {
    newTodos.splice(index, 1);
    newTodos.forEach((todo, i) => {
        todo.rowID = i
    })
}

// add new maintenance visit template
const addMVT = async () => {
    // check if all input data is valid
    if (newNameMVT.value.trim() === "") {
        alert("Please add a maintenance visit template name!");
        return;
    } else {
        var counter = 0;
        if (!(maintenanceVisitTemplates.value.length == null)) {
            // check if maintenance visit template name already exists
            maintenanceVisitTemplates.value.forEach(MVT => {
                if (MVT.name === newNameMVT.value) {
                    counter += 1;
                }
            });
            if (counter == 1) {
                alert("This maintenance visit template name already exists. Please choose an unique maintenance visit template name or modify respectively delete the old one!");
                return;
            }
        }
    }
    if (newCustomerMVT.value.length === 0) {
        alert("Please choose a client!");
        return;
    }
    let allFine = true;
    newTodos.forEach(todo => {
        if (todo.asset.length === 0) {
            alert(`Please choose a config item for all todos.`);
            allFine = false
        }
    })
    if (!allFine) {
        return
    }
    try {
        const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addMVT`,
            {
                name: newNameMVT.value,
                customerID: newCustomerIDMVT.value,
                customer: newCustomerMVT.value,
                lastView: newLastViewMVT.value,
                user: newUserMVT.value,
                type: newTypeMVT.value,
                notes: newNotesMVT.value,
            });
        store.commit('resetStore');
        store.commit('changeToTemplatelist');
        newTodos.forEach(async todo => {
            try {
                const res = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addTodoMVT`,
                    {
                        templateID: response.data,
                        rowID: todo.rowID,
                        asset: todo.asset,
                        task: todo.task,
                        comment: todo.comments,
                    });
            } catch (err) {
                console.log(err.response.statusText);
            }
        })
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new row of todo for the new MVT
const addRowForNewMVT = async () => {
    if (newCustomerMVT.value.length === 0) {
        alert("Please choose a client first!");
        return;
    }
    await getConfigItemsFromClient();
    newTodos.push({
        templateID: chosenMVTId.value,
        rowID: newRowId.value,
        asset: '',
        task: '',
        comments: ''
    });
}

//update data
const updateMVTTodo = async (todo) => {
    if (todo.asset.length === 0) {
        alert(`Please add the missing config item in row ${todo.rowID}!`);
        return;
    }
    try {
        await Axios.put(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateMVTTodo`,
            {
                primaryID: todo.primaryID,
                templateID: todo.templateID,
                rowID: todo.rowID,
                asset: todo.asset,
                task: todo.task,
                comments: todo.commets,
            }
        );
        await getMVTById();
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new maintenance visit template todo
const addMVTTodo = async () => {
    // check if all input data is valid
    if (newAssetTodo.value.length === 0) {
        alert("Please choose an asset for the new todo!");
        return;
    }
    try {
        const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addTodoMVT`,
            {
                templateID: chosenMVTId.value,
                rowID: newStepTodo.value,
                asset: newAssetTodo.value,
                task: newTaskTodo.value,
                comment: newCommentsTodo.value,
            });
        addRow.value = false;
        await getMvtTodosById();
        newAssetTodo.value = '';
        newTaskTodo.value = '';
        newCommentsTodo.value = '';
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new row for the template checklist
const addChecklistRow = async () => {
    await getConfigItemsFromClient();
    if (addRow.value) {
        alert('Please confirm the last added row first.')
        return
    }
    addRow.value = true
}

//get all maintenance visit templates
const getMaintenanceVisitTemplates = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getAllMaintenanceVisitTemplates`);
        maintenanceVisitTemplates.value = response.data;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// include delay to avoid 503 error
const triggerBackendCallsWithDelay = async (fetchDataFunc) => {
    setTimeout(() => {
        fetchDataFunc();
    }, 1000);
}

// get maintenance visit template todos from id
const getMvtTodosById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosMaintenanceVisitTemplate/${chosenMVTId.value}`
            );
            mvtTodos.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

//get all config items from the selected client
const getConfigItemsFromClient = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCIFromClient/${MVT.value.customerID}`);
            configItemList.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCIFromClient/${changedClientId.value}`);
            configItemList.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    if (clientChanged.value) {
        store.commit('toggleClientChanged');
    }
}

// get maintenance visit template from id
const getMVTById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getMaintenanceVisitTemplate/${chosenMVTId.value}`
            );
            MVT.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    await getConfigItemsFromClient();
}

const deleteMVTTodo = async (id) => {
    if (confirm("Do you really want to delete this maintenance visit template todo? It cannot be undone!")) {
        try {
            await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteMVTTodo/${id}`);
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    await getMvtTodosById();
}

watch(clientChanged, getMVTById);

onMounted(() => {
    getMvtTodosById();
    getMVTById();
    triggerBackendCallsWithDelay(getMaintenanceVisitTemplates);
});
</script>

<script>
export default {
    name: "TemplateChecklist",
};
</script> 
  
    
<style scoped>
.data {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    padding: 0 0.625rem;
    border-radius: 0.3125rem;
    box-shadow: 0.0625rem 0.0625rem 0.25rem 0rem rgba(0, 0, 0, 0.25) inset;
    letter-spacing: 5%;
    font: 400 0.75rem/250% Overpass, sans-serif;
}

.section-darkmode {
    background-color: #2c2c2c;
}

.section-lightmode {
    background-color: #fff;
}

.data-darkmode {
    background-color: #212121;
    color: #fff;
}

.data-lightmode {
    background-color: #EBEBEB;
    color: #000;
}

.select-darkmode {
    border: none;
    color: white;
    background: #212121;
    padding: 0.4rem;
    border-radius: 0.3125rem;
}

.select-lightmode {
    border: none;
    color: black;
    background: #EBEBEB;
    padding: 0.4rem;
    border-radius: 0.3125rem;
}

.input {
    border: none;
}

.data-table {
    width: 100%;
    padding: 0 0.625rem;
    table-layout: fixed;
    border-collapse: collapse;
}

.table-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 3.125rem;
    padding: 0.625rem;
    gap: 0.625rem;
}

.tr-head-darkmode {
    border-top: none;
    border-bottom: 0.0625rem solid #000000;
}

.tr-head-lightmode {
    border-top: none;
    border-bottom: 0.0625rem solid #8e8e8e;
}

.tr-darkmode {
    border-top: 0.0625rem solid #000000;
}

.tr-lightmode {
    border-top: 0.0625rem solid #8e8e8e;
}

th,
td {
    height: 1.875rem;
    text-align: left;
    padding: 0;
    letter-spacing: 5%;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

th {
    font: 700 0.875rem/1.875rem Overpass, sans-serif;
}

.th-darkmode,
.td-darkmode {
    color: #ffffff;
}

.th-lightmode,
.td-lightmode {
    color: #000;
}

.template-checklist-information {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    padding: 1.25rem 1.875rem;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.Step {
    width: 8%;
}

.Step-darkmode {
    border-right: 0.0625rem solid #000000;
}

.Step-lightmode {
    border-right: 0.0625rem solid #8e8e8e;
}

.Asset {
    width: 22%;
}

.Asset-darkmode {
    border-right: 0.0625rem solid #000000;
}

.Asset-lightmode {
    border-right: 0.0625rem solid #8e8e8e;
}

.Task {
    width: 35%;
}

.Task-darkmode {
    border-right: 0.0625rem solid #000000;
}

.Task-lightmode {
    border-right: 0.0625rem solid #8e8e8e;
}

.Comments {
    width: 35%;
    display: flex;
}

.label {
    width: 6.0625em;
    height: 1.875em;
    font-family: 'Overpass';
    font-style: normal;
    font-weight: 400;
    font-size: 1em;
    line-height: 1.875em;
    letter-spacing: 0.05em;
}

.label-darkmode {
    color: #FFFFFF;
}

.label-lightmode {
    color: #000;
}

.editMvtTodos-darkmode {
    background: #2c2c2c;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 0.825rem 0.7rem;
    width: 4%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}


.saveMvtTodos-darkmode {
    background: #212121;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 10rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.saveNewMVT-darkmode {
    background: #2c2c2c;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 1rem 1.875rem;
    width: 8%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.deleteMvtTodos-darkmode {
    background: #212121;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 15.8rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.deleteLastMvtTodos-darkmode {
    background: #212121;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 2rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}


.editMvtTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    margin-left: 15rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
    border-radius: 0.625rem;
}

.saveMvtTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 10rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.deleteMvtTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 15.8rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.deleteLastMvtTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 2rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.saveNewMVT-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 1rem 1.875rem;
    width: 8%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.deleteMvtTodos-darkmode:hover,
.deleteLastMvtTodos-darkmode:hover,

.saveMvtTodos-darkmode:hover,
.editMvtTodos-darkmode:hover,
.saveNewMVT-darkmode:hover {
    background-color: #444444;
    cursor: pointer;
}

.deleteMvtTodos-lightmode:hover,
.deleteLastMvtTodos-lightmode:hover,

.saveMvtTodos-lightmode:hover,
.editMvtTodos-lightmode:hover,
.saveNewMVT-lightmode:hover {
    background-color: #ACACAC;
    cursor: pointer;
}

#saveNewMVT {
    text-align: center;
}

#editMvtTodos {
    text-align: right;
}
</style>