<template>
    <section :class="['instance-checklist-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'label-darkmode' : 'label-lightmode']">Checklist:</div>
        <table class="data-table" id="instance-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', darkMode ? 'Comments-darkmode' : 'Comments-lightmode']">
                        Comments</th>
                    <th v-if="!addBool" :class="['Done', darkMode ? 'th-darkmode' : 'th-lightmode']">Done</th>
                </tr>
                <tr v-for="todo in mviTodos" :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
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        {{ todo.asset }}</td>
                    <td
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        {{ todo.task }}</td>
                    <td v-if="!editable"
                        :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Comments-darkmode' : 'Comments-lightmode']">
                        {{ todo.comments }}</td>
                    <td v-if="editable" :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"> <input
                            type="text" v-model="todo.comments" @change="updateMVITodo(todo)"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </td>
                    <td v-if="!addBool" :class="['Done', darkMode ? 'td-darkmode' : 'td-lightmode']"><input
                            @change="toggleTodo(todo)" type="checkbox" v-model="todo.done"
                            :class="[darkMode ? 'checkbox-darkmode' : 'checkbox-lightmode']" /></td>
                </tr>
            </tbody>
        </table>
    </section>
    <section v-if="addBool" id="saveNewMVI">
        <button :class="[darkMode ? 'saveNewMVI-darkmode' : 'saveNewMVI-lightmode']" @click="addMVI()">Save</button>
    </section>
</template>

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

const store = useStore();
const modeChanged = computed(() => store.state.updateDarkMode);

const chosenMVIId = computed(() => store.state.chosenMITId);
const chosenMVTId = computed(() => store.state.chosenMVTId);

const addBool = computed(() => store.state.new);
const newNameMVI = computed(() => store.state.newNameMVI);
const newTemplateIDMVI = computed(() => store.state.newTemplateIDMVI);
const newMaintenanceTypeMVI = computed(() => store.state.newMaintenanceTypeMVI);
const newStateMVI = computed(() => store.state.newStateMVI);
const newCreationDateMVI = computed(() => store.state.newCreationDateMVI);
const newCompletionDateMVI = computed(() => store.state.newCompletionDateMVI);
const newUserMVI = computed(() => store.state.newUserMVI);
const newCustomerIDMVI = computed(() => store.state.newCustomerIDMVI);
const newCustomerMVI = computed(() => store.state.newCustomerMVI);
const newTemplateNotesMVI = computed(() => store.state.newTemplateNotesMVI);
const newTypeMVI = computed(() => store.state.newTypeMVI);
const newTimeSpentMVI = computed(() => store.state.newTimeSpentMVI);
const newNotesMVI = computed(() => store.state.newNotes);
const editable = computed(() => store.state.editable);

const darkMode = ref('');
const mviTodos = ref([]);
const maintenanceVisitInstances = ref([]);

const getSession = async () => {
    const loggedInUserDarkModeBool = getItem('logged-in-user-darkMode');
    if (loggedInUserDarkModeBool == 1) {
        darkMode.value = true;
    } else {
        darkMode.value = false;
    }
}

// get maintenance visit template todos from id
const getMVITodosById = async () => {
    if (chosenMVTId.value != -1 && addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosMaintenanceVisitTemplate/${chosenMVTId.value}`
            );
            mviTodos.value = response.data;
            store.commit('updateMaintenanceVisitInstanceTemplateID', chosenMVTId.value)
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else if (addBool.value && !(newTemplateIDMVI.value == '')) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosMaintenanceVisitTemplate/${newTemplateIDMVI.value}`
            );
            mviTodos.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosMaintenanceVisitInstance/${chosenMVIId.value}`
            );
            const mviTodosComment = response.data;
            // change the comment und step field name to comments and rowID
            mviTodos.value = mviTodosComment.map(obj => {
                const { step: rowID, comment: comments, ...rest } = obj;
                return { ...rest, rowID, comments };
            });
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    mviTodos.value = mviTodos.value.map(obj => ({
        // convert 'done' to boolean
        ...obj,
        done: obj.done === "1"
    }));
}

const toggleTodo = (todo) => {
    let doneInput = false;
    doneInput = todo.done;
    updateMVITodo(todo, true, doneInput);
}

//update data
const updateMVITodo = async (todo, doneChanged = false, doneInput = false) => {
    if (doneChanged) {
        todo.done = doneInput;
    }
    if (todo.done) {
        todo.done = 1;
    }
    try {
        await Axios.put(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateMVITodo`,
            {
                primaryID: todo.primaryID,
                step: todo.rowID,
                asset: todo.asset,
                task: todo.task,
                comment: todo.comments,
                done: todo.done,
            }
        );
        await getMVITodosById();
    } catch (err) {
        console.log(err.response.statusText);
    }
}

function getItem(item) {
    if (process.client) {
        return localStorage.getItem(item)
    } else {
        return undefined
    }
}

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

// add new maintenance visit instance
const addMVI = async () => {
    // check if all input data is valid
    if (newNameMVI.value.trim() === "") {
        alert("Please add a maintenance visit instance name!");
        return;
    } else {
        var counter = 0;
        if (!(maintenanceVisitInstances.value.length == null)) {
            // check if maintenance visit instance name already exists
            maintenanceVisitInstances.value.forEach(m => {
                if (m.name === newNameMVI.value) {
                    counter += 1;
                }
            });
            if (counter == 1) {
                alert("This maintenance visit instance name already exists. Please choose an unique maintenance visit instance name or modify respectively delete the old one!");
                return;
            }
        }
    }
    if (newCustomerMVI.value.length === 0) {
        alert("Please choose a customer!");
        return;
    }
    // get the time and date
    const today = new Date();
    const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
    const time = today.getHours() + ":" + today.getMinutes();
    const dateTime = date + ' ' + time;
    try {
        const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addMVI`,
            {
                name: newNameMVI.value,
                templateID: newTemplateIDMVI.value,
                maintenanceType: newMaintenanceTypeMVI.value,
                state: newStateMVI.value,
                creationDate: dateTime,
                completionDate: newCompletionDateMVI.value,
                user: newUserMVI.value,
                customerID: newCustomerIDMVI.value,
                customer: newCustomerMVI.value,
                templateNotes: newTemplateNotesMVI.value,
                type: newTypeMVI.value,
                timeSpent: newTimeSpentMVI.value,
                notes: newNotesMVI.value,
            });
        store.commit('resetStore');
        store.commit('changeToInstancelist');
        store.commit('seeAllIcon');
        mviTodos.value.forEach(async todo => {
            try {
                const res = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addTodoMVI`,
                    {
                        templateID: response.data,
                        step: todo.rowID,
                        asset: todo.asset,
                        task: todo.task,
                        comment: todo.comments,
                        done: false,
                    });
            } catch (err) {
                console.log(err.response.statusText);
            }
        })
    } catch (err) {
        console.log(err.response.statusText);
    }
}

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

watch(modeChanged, getSession)
watch(newTemplateIDMVI, getMVITodosById)

onMounted(async () => {
    getSession();
    await getMVITodosById();
    triggerBackendCallsWithDelay(getMaintenanceVisitInstances);
});
</script>

<script>
export default {
    name: "InstanceChecklistMVI",
};
</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;
}

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

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

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

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

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

.input {
    border: none;
}

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

.saveNewMVI-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);
}

.saveNewMVI-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);
}

.saveNewMVI-darkmode:hover {
    background-color: #444444;
    cursor: pointer;
}

.saveNewMVI-lightmode:hover {
    background-color: #ACACAC;
    cursor: pointer;
}

#saveNewMVI {
    text-align: center;
}

.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;
}

.checkbox-darkmode {
    filter: invert(100%);
}

.checkbox-lightmode {
    filter: invert(0%);
}

.instance-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);
}

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

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

.Step {
    width: 7%;
}

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

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

.Asset {
    width: 28%;
}

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

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

.Task {
    width: 30%;
}

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

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

.Comments {
    width: 30%;
}

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

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

.Done {
    width: 5%;
}

.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;
}
</style>