<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 poiTodos" :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="updatePOITodo(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="saveNewPOI">
        <button :class="[darkMode ? 'saveNewPOI-darkmode' : 'saveNewPOI-lightmode']" @click="addPOI()">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 chosenPOTId = computed(() => store.state.chosenPOTId);
const chosenPOIId = computed(() => store.state.chosenPOIId);

const addBool = computed(() => store.state.new);
const newNamePOI = computed(() => store.state.newNamePOI);
const newTemplateIDPOI = computed(() => store.state.newTemplateIDPOI);
const newCustomerIDPOI = computed(() => store.state.newCustomerIDPOI);
const newCustomerPOI = computed(() => store.state.newCustomerPOI);
const newAssetPOI = computed(() => store.state.newAssetPOI);
const newStatePOI = computed(() => store.state.newStatePOI);
const newCreationDatePOI = computed(() => store.state.newCreationDatePOI);
const newCompletionDatePOI = computed(() => store.state.newCompletionDatePOI);
const newUserPOI = computed(() => store.state.newUserPOI);
const newTemplateDescriptionPOI = computed(() => store.state.newTemplateDescriptionPOI);
const newTemplateNotesPOI = computed(() => store.state.newTemplateNotesPOI);
const newTimeSpentPOI = computed(() => store.state.newTimeSpentPOI);
const newNotesPOI = computed(() => store.state.newNotes);
const editable = computed(() => store.state.editable);

const darkMode = ref('');
const poiTodos = ref([]);
const productionOrderInstances = ref([]);

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

// get production order template todos from id
const getPOITodosById = async () => {
    if (chosenPOTId.value != -1 && addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosProductionOrderTemplate/${chosenPOTId.value}`
            );
            poiTodos.value = response.data;
            store.commit('updateProductionOrderInstanceTemplateID', chosenPOTId.value)
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else if (addBool.value && !(newTemplateIDPOI.value == '')) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosProductionOrderTemplate/${newTemplateIDPOI.value}`
            );
            poiTodos.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosProductionOrderInstance/${chosenPOIId.value}`
            );
            const poiTodosComment = response.data;
            // change the comment und step field name to comments and rowID
            poiTodos.value = poiTodosComment.map(obj => {
                const { step: rowID, comment: comments, ...rest } = obj;
                return { ...rest, rowID, comments };
            });
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    poiTodos.value = poiTodos.value.map(obj => ({
        // convert 'done' to boolean
        ...obj,
        done: obj.done === "1"
    }));
}

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

//update data
const updatePOITodo = 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/updatePOITodo`,
            {
                primaryID: todo.primaryID,
                step: todo.rowID,
                asset: todo.asset,
                task: todo.task,
                comment: todo.comments,
                done: todo.done,
            }
        );
        await getPOITodosById();
    } catch (err) {
        console.log(err.response.statusText);
    }
}

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

//get all productionOrder instances
const getProductionOrderInstances = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getAllProductionOrderInstances`);
        productionOrderInstances.value = response.data;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new production order instance
const addPOI = async () => {
    // check if all input data is valid
    if (newNamePOI.value.trim() === "") {
        alert("Please add a production order instance name!");
        return;
    } else {
        var counter = 0;
        if (!(productionOrderInstances.value.length == null)) {
            // check if production order instance name already exists
            productionOrderInstances.value.forEach(p => {
                if (p.name === newNamePOI.value) {
                    counter += 1;
                }
            });
            if (counter == 1) {
                alert("This production order instance name already exists. Please choose an unique production order instance name or modify respectively delete the old one!");
                return;
            }
        }
    }
    if (newCustomerPOI.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/addPOI`,
            {
                name: newNamePOI.value,
                templateID: newTemplateIDPOI.value,
                customerID: newCustomerIDPOI.value,
                customer: newCustomerPOI.value,
                asset: newAssetPOI.value,
                state: newStatePOI.value,
                creationDate: dateTime,
                completionDate: newCompletionDatePOI.value,
                user: newUserPOI.value,
                templateDescription: newTemplateDescriptionPOI.value,
                templateNotes: newTemplateNotesPOI.value,
                timeSpent: newTimeSpentPOI.value,
                notes: newNotesPOI.value,
            });
        store.commit('resetStore');
        store.commit('changeToInstancelist');
        store.commit('seeAllIcon');
        poiTodos.value.forEach(async todo => {
            try {
                const res = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addTodoPOI`,
                    {
                        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(newTemplateIDPOI, getPOITodosById)

onMounted(async () => {
    getSession();
    await getPOITodosById();
    triggerBackendCallsWithDelay(getProductionOrderInstances);
});
</script>

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

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

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

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

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

#saveNewPOI {
    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>