<template>
    <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <h2 v-if="!editable" :class="['maintenance-visits-instance-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{
        mvi.name }}</h2>
        <input v-if="editable" v-model="mvi.name" @change="updateMVI()"
            :class="['data', 'mvi-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="maintenance-visits-instance-data">
            <div class="instanceInfo">
                <div class="data-field" id="info">
                    <div class="templateId-customer-type" id="templateID">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Template ID:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.templateID }}</pre>
                    </div>
                    <div class="templateId-customer-type" id="customer">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.customer }}</pre>
                    </div>
                    <div class="templateId-customer-type" id="type">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Type:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.type }}</pre>
                        <input v-if="editable" v-model="mvi.type" @change="updateMVI()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="maintenance-visits-instance-data">
            <div class="additionaFl">
                <div class="templateNotes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Template notes:</h3>
                    <pre v-if="!editable" :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"
                        id="templateNotes">{{ mvi.templateNotes }}</pre>
                    <input v-if="editable" v-model="mvi.templateNotes" @change="updateMVI()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
        </div>
        <div class="maintenance-visits-instance-data">
            <div class="instanceInfo">
                <div class="data-field" id="info">
                    <div class="maintenanceType-state-user" id="maintenanceType">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Maintenance type:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.maintenanceType }}</pre>
                        <input v-if="editable" v-model="mvi.maintenanceType" @change="updateMVI()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="maintenanceType-state-user" id="state">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">State:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.state }}</pre>
                        <input v-if="editable" v-model="mvi.state" @change="updateMVI()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="maintenanceType-state-user" id="user">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">User:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.user }}</pre>
                        <select v-if="editable" id="assetsDropDownChosenCI" v-model="mvi.user" @change="updateMVI()"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="user in userList" :key="user.id">
                                {{ user.username }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="data-field" id="info">
                    <div class="creationDate-completionDate-timeSpent" id="creationDate">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Creation date:</pre>
                        <pre
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.creationDate }}</pre>
                    </div>
                    <div class="creationDate-completionDate-timeSpent" id="completionDate">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Completion date:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.completionDate }}</pre>
                        <input v-if="editable" v-model="mvi.completionDate" @change="updateMVI()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="creationDate-completionDate-timeSpent" id="timeSpent">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Time spent:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.timeSpent }}</pre>
                        <input v-if="editable" v-model="mvi.timeSpent" @change="updateMVI()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="maintenance-visits-instance-data">
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="mvi.notes" :readonly="!editable" @change="updateMVI()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <input v-model="newName" @change="updateMaintenanceVisitInstance()"
            :class="['data', 'mvi-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="maintenance-visits-instance-data">
            <div class="instanceInfo">
                <div class="data-field" id="info">
                    <div class="templateId-customer-type" id="templateID">
                        <pre v-if="mvtSelected"
                            :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Template ID:</pre>
                        <pre v-if="!mvtSelected"
                            :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Template name:</pre>
                        <pre v-if="mvtSelected"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ chosenMVTId }}</pre>
                        <select v-if="!mvtSelected" id="assetsDropDownChosenCI" v-model="chosenTemplate"
                            @change="updateMaintenanceVisitInstance(chosenTemplate)"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="template in maintenanceVisitTemplates" :key="template.checklistID">
                                {{ template.name }}
                            </option>
                        </select>
                    </div>
                    <div class="templateId-customer-type" id="customer">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ mvi.customer }}</pre>
                    </div>
                    <div class="templateId-customer-type" id="type">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Type:</pre>
                        <input v-model="newType" @change="updateMaintenanceVisitInstance()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
            </div>
        </div>
        <div class="maintenance-visits-instance-data">
            <div class="additionaFl">
                <div class="templateNotes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Template notes:</h3>
                    <input v-model="newTemplateNotes" @change="updateMaintenanceVisitInstance()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
        </div>
        <div class="maintenance-visits-instance-data">
            <div class="instanceInfo">
                <div class="data-field" id="info">
                    <div class="maintenanceType-state-user" id="maintenanceType">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Maintenance type:</pre>
                        <input v-model="newMaintenanceType" @change="updateMaintenanceVisitInstance()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="maintenanceType-state-user" id="state">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">State:</pre>
                        <input v-model="newState" @change="updateMaintenanceVisitInstance()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="maintenanceType-state-user" id="user">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">User:</pre>
                        <select id="assetsDropDownChosenCI" v-model="newUser" @change="updateMaintenanceVisitInstance()"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="user in userList" :key="user.id">
                                {{ user.username }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="data-field" id="info">
                    <div class="creationDate-completionDate-timeSpent" id="creationDate">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Creation date:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
                    </div>
                    <div class="creationDate-completionDate-timeSpent" id="completionDate">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Completion date:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
                    </div>
                    <div class="creationDate-completionDate-timeSpent" id="timeSpent">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Time spent:</pre>
                        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
                    </div>
                </div>
            </div>
        </div>
        <div class="maintenance-visits-instance-data">
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="newNotes" @change="updateMaintenanceVisitInstance()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
                </div>
            </div>
        </div>
    </section>
</template>


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

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

const editable = computed(() => store.state.editable);
const chosenMVIId = computed(() => store.state.chosenMITId);
const chosenMVTId = computed(() => store.state.chosenMVTId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);

const darkMode = ref('');
const mvtSelected = ref('');

const mvi = ref({});
const mvt = ref({});
const customers = ref([]);

const newName = ref('');
const newTemplateID = ref('');
const chosenTemplate = ref('');
const newCustomerID = ref('');
const newCustomer = ref('');
const newMaintenanceType = ref('');
const newUser = ref('');
const newState = ref('');
const newNotes = ref('');
const newTemplateNotes = ref('');
const newType = ref('');
const newCreationDate = ref('');
const newCompletionDate = ref('');
const newTimeSpent = ref('');
const maintenanceVisitInstances = ref([]);
const maintenanceVisitTemplates = ref([]);
const userList = ref([]);

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

//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);
    }
}

// get maintenance visit template from id
const getMVTById = async () => {
    if (chosenMVTId.value == '-1') {
        mvtSelected.value = false;
        await getMaintenanceVisitTemplates();
    } else {
        mvtSelected.value = true;
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getMaintenanceVisitTemplate/${chosenMVTId.value}`
            );
            mvt.value = response.data;
            mvi.value.customer = mvt.value.customer;
            mvi.value.customerID = mvt.value.customerID;
            newCustomer.value = mvt.value.customer;
            newCustomerID.value = mvt.value.customerID;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    await getMaintenanceVisitInstances();
}

// get maintenance visit template from id
const getChosenMVTById = async (newMvtId) => {
    try {
        const response = await Axios.get(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getMaintenanceVisitTemplate/${newMvtId}`
        );
        mvt.value = response.data;
        mvi.value.customer = mvt.value.customer;
        mvi.value.customerID = mvt.value.customerID;
        newCustomer.value = mvt.value.customer;
        newCustomerID.value = mvt.value.customerID;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

const confirmDeleteMVI = async () => {
    if (deleteBool.value === true) {
        if (confirm("Do you really want to delete this maintenance visit instance? It cannot be undone!")) {
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteMaintenanceVisitInstance/${chosenMVIId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteTodosMVI/${chosenMVIId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
            store.commit('undoDelete');
            store.commit('resetStore');
            store.commit('deactivateSearch');
            store.commit('changeToInstancelist');
            store.commit('seeAllIcon');
        } else {
            store.commit('undoDelete');
        }
    }
}

//get all users
const getUsers = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getAllEmployees`);
        userList.value = response.data;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

//update data
const updateMVI = async () => {
    if (mvi.value.name.trim() === "") {
        alert("Please add a maintenance visit instance name!");
        return;
    } else {
        var counter = 0;
        // check if maintenance visit instance name already exists
        maintenanceVisitInstances.value.forEach(m => {
            if (m.name === mvi.value.name) {
                counter += 1;
            }
        });
        if (counter == 2) {
            alert("This maintenance visit instance name already exists. Please choose an unique maintenance visit instance name or modify respectively delete the old one!");
            mvi.value.name = '';
            return;
        }
        try {
            await Axios.put(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateMaintenanceVisitInstance`,
                {
                    primaryID: mvi.value.primaryID,
                    name: mvi.value.name,
                    templateID: mvi.value.templateID,
                    maintenanceType: mvi.value.maintenanceType,
                    state: mvi.value.state,
                    creationDate: mvi.value.creationDate,
                    completionDate: mvi.value.completionDate,
                    user: mvi.value.user,
                    customerID: mvi.value.customerID,
                    customer: mvi.value.customer,
                    type: mvi.value.type,
                    templateNotes: mvi.value.templateNotes,
                    timeSpent: mvi.value.timeSpent,
                    notes: mvi.value.notes,
                }
            )
            await getMVIById();
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

//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);
    }
}

// update maintenance visit instance fields in the store
const updateMaintenanceVisitInstance = async (newMvtId = -1) => {
    let maintenanceVisitInstance = {};
    if (mvtSelected.value) {
        maintenanceVisitInstance = {
            name: newName.value,
            templateID: chosenMVTId.value,
            maintenanceType: newMaintenanceType.value,
            state: newState.value,
            creationDate: newCreationDate.value,
            completionDate: newCompletionDate.value,
            user: newUser.value,
            customerID: newCustomerID.value,
            customer: newCustomer.value,
            templateNotes: newTemplateNotes.value,
            type: newType.value,
            timeSpent: newTimeSpent.value,
            notes: newNotes.value,
        };
    } else {
        if (!(newMvtId == '-1')) {
            // Find the object with the selected Name
            const selectedObject = maintenanceVisitTemplates.value.find(obj => obj.name === newMvtId);
            // Get the templateID
            newTemplateID.value = selectedObject ? selectedObject.checklistID : null;
            await getChosenMVTById(newTemplateID.value);
        }
        maintenanceVisitInstance = {
            name: newName.value,
            templateID: newTemplateID.value,
            maintenanceType: newMaintenanceType.value,
            state: newState.value,
            creationDate: newCreationDate.value,
            completionDate: newCompletionDate.value,
            user: newUser.value,
            customerID: newCustomerID.value,
            customer: newCustomer.value,
            templateNotes: newTemplateNotes.value,
            type: newType.value,
            timeSpent: newTimeSpent.value,
            notes: newNotes.value,
        };
    }
    store.commit('updateMaintenanceVisitInstanceComponent', maintenanceVisitInstance);
}

// get maintenance visit instance from id
const getMVIById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getMaintenanceVisitInstance/${chosenMVIId.value}`
            );
            mvi.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

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

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

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

watch(modeChanged, getSession)
watch(deleteBool, confirmDeleteMVI);

onMounted(async () => {
    getSession();
    await getMVIById();
    await getMVTById();
    triggerBackendCallsWithDelay(getUsers);
    triggerBackendCallsWithDelay(getCustomers);
});
</script>

<script>
export default {
    name: "MaintenanceVisitsInstance",
};
</script>


<style scoped>
.information {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    width: 100%;
    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;
}



.maintenance-visits-instance-name {
    align-self: stretch;
    padding: 1rem 0;
    letter-spacing: 5%;
    text-decoration-line: underline;
    font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
        sans-serif;
}

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

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

.h2-darkmode {
    color: #fff;
}

.h2-lightmode {
    color: #000;
}

.data-field {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    width: 95%;
    padding: 0.8rem 1.875rem;
    gap: 1.25rem;
    border-radius: 0.625rem;
}

.maintenanceType-state-user,
.creationDate-completionDate-timeSpent,
.templateId-customer-type {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    width: 100%;
    padding: 0 0rem;
    gap: 1.25rem;
    border-radius: 0.625rem;
}

.label {
    letter-spacing: 5%;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

.pre-darkmode {
    color: #fff;
}

.pre-lightmode {
    color: #000;
}

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

.h2-darkmode {
    color: #fff;
}

.h2-lightmode {
    color: #000;
}

.h2-input-darkmode {
    background-color: #212121;
}

.h2-input-lightmode {
    background-color: #EBEBEB;
}

.input {
    border: none;
}

.mvi-name-input {
    /* padding: 1rem 0; */
    margin: 1rem;
    font-size: initial;
    letter-spacing: 5%;
    text-decoration-line: underline;
    font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
        sans-serif;
}

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

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

.maintenance-visits-instance-data {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    align-self: stretch;
}

.instanceInfo,
.info {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    line-height: normal;
    width: 100%;
    padding: 0 0;
    border-radius: 0.3125rem;
}

.additional {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    line-height: normal;
    width: 100%;
    padding: 0rem 0.625rem;
    border-radius: 0.3125rem;
}

.area-title {
    letter-spacing: 5%;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

.h3-darkmode {
    color: #fff;
}

.h3-lightmode {
    color: #000;
}

.data#templateNotes,
.data#notes {
    align-self: stretch;
}

.notes,
.templateNotes {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    align-self: stretch;
    padding: 0.625rem 1.875rem 0.625rem 1.25rem;
    padding-top: 0rem;
}

.templateNotes {
    padding-left: 1.8rem;
}
</style>