<template>
    <section v-if="searchable" :class="['mvi-search', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['instanceLabel', darkMode ? 'label-darkmode' : 'label-lightmode']">State</div>
        <input v-model="stateSearchFilter" @change="filterMVIByState()"
            :class="['dataInput', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
    </section>
    <section v-if="filtered" :class="['mvi-search', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['instanceLabel', darkMode ? 'label-darkmode' : 'label-lightmode']">User</div>
        <input v-model="userSearchFilter" @change="filterInstancesByUser()"
            :class="['dataInput', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
    </section>
    <div :class="['data', darkMode ? 'div-darkmode' : 'div-lightmode']">
        <div :class="['label', darkMode ? 'label-darkmode' : 'label-lightmode']">Instances:</div>
        <table class="data-table" name="maintenance-visits-instance-table">
            <tbody>
                <tr :class="['table-row', darkMode ? 'tr-head-darkmode' : 'tr-head-lightmode']" id="table-head">
                    <th
                        :class="['ID', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'ID-darkmode' : 'ID-lightmode']">
                        ID</th>
                    <th
                        :class="['MaintenanceType', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'MaintenanceType-darkmode' : 'MaintenanceType-lightmode']">
                        Maintenance type</th>
                    <th
                        :class="['State', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'State-darkmode' : 'State-lightmode']">
                        State</th>
                    <th
                        :class="['CreationDate', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'CreationDate-darkmode' : 'CreationDate-lightmode']">
                        Creation date</th>
                    <th
                        :class="['CompletionDate', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'CompletionDate-darkmode' : 'CompletionDate-lightmode']">
                        Completion date</th>
                    <th :class="['User', darkMode ? 'th-darkmode' : 'th-lightmode']">User</th>
                </tr>
                <tr v-for="instance in maintenanceVisitInstances" :key="instance.primaryID"
                    :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                    <td
                        :class="['ID', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'ID-darkmode' : 'ID-lightmode']">
                        <nuxt-link to="/maintenanceVisits" id="nuxt-link" class="button"
                            :class="[darkMode ? 'button-darkmode' : 'button-lightmode', darkMode ? 'nuxt-link-darkmode' : 'nuxt-link-lightmode']"
                            @click="goToChosenMVI(instance.primaryID)">
                            {{ instance.primaryID }}
                        </nuxt-link>
                    </td>
                    <td
                        :class="['MaintenanceType', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'MaintenanceType-darkmode' : 'MaintenanceType-lightmode']">
                        {{ instance.maintenanceType }}</td>
                    <td
                        :class="['State', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'State-darkmode' : 'State-lightmode']">
                        {{ instance.state }}</td>
                    <td
                        :class="['CreationDate', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'CreationDate-darkmode' : 'CreationDate-lightmode']">
                        {{ instance.creationDate }}</td>
                    <td
                        :class="['CompletionDate', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'CompletionDate-darkmode' : 'CompletionDate-lightmode']">
                        {{ instance.completionDate }}</td>
                    <td :class="['User', darkMode ? 'td-darkmode' : 'td-lightmode']">{{ instance.user }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</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 chosenMVTId = computed(() => store.state.chosenMVTId);
const searchable = computed(() => store.state.searchable);
const filtered = computed(() => store.state.filtered);
const notAllInstancesIcon = computed(() => store.state.notAllInstancesIcon);
const userSearchFilter = ref('');
const stateSearchFilter = ref('');
const maintenanceVisitInstances = ref([]);

const darkMode = ref('');
const mvt = ref({});
const MVIByUser = ref([]);
const MVIByState = ref([]);

const goToChosenMVI = (id) => {
    store.commit('setChosenMIT', id);
    store.commit('changeToInstance');
};

//get all maintenance visit instances
const getMaintenanceVisitInstances = async () => {
    if (notAllInstancesIcon.value) {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getSelectedMVIByMVT/${mvt.value.checklistID}`);
            maintenanceVisitInstances.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        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 search term
const updateSearchTerm = async () => {
    stateSearchFilter.value = '';
    await getMaintenanceVisitInstances();
}

// update filter term
const updateFilterTerm = async () => {
    userSearchFilter.value = '';
    await getMaintenanceVisitInstances();
}

// get maintenance visit template from id
const getMVTById = async () => {
    if (notAllInstancesIcon.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 getMaintenanceVisitInstances();
}

//get all instances based on the searched state
const filterMVIByState = async () => {
    if (stateSearchFilter.value === '') {
        await getMaintenanceVisitInstances();
    } else {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getSelectedMVIByState/${stateSearchFilter.value}`);
            MVIByState.value = response.data;
            maintenanceVisitInstances.value = filterObjectsWithMatchingIds(maintenanceVisitInstances.value, MVIByState.value);
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

//get all instances based on the searched user
const filterInstancesByUser = async () => {
    if (userSearchFilter.value === '') {
        await getMaintenanceVisitInstances();
    } else {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getSelectedMVIByUser/${userSearchFilter.value}`);
            MVIByUser.value = response.data;
            maintenanceVisitInstances.value = filterObjectsWithMatchingIds(maintenanceVisitInstances.value, MVIByUser.value);
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

const filterObjectsWithMatchingIds = (arr1, arr2) => {
    return arr1.filter(obj1 => {
        return arr2.some(obj2 => obj2.primaryID === obj1.primaryID);
    });
};

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(searchable, updateSearchTerm);
watch(filtered, updateFilterTerm);
watch(notAllInstancesIcon, getMaintenanceVisitInstances);

onMounted(async () => {
    getSession();
    await getMVTById();
});
</script>

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



<style scoped>
.data {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    align-self: stretch;
    width: 100%;
    padding: 1.25rem 1.875rem;
    gap: 1.25rem;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

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

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

.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-darkmode,
.td-darkmode {
    color: #ffffff;
}

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

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

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

.mvi-search {
    display: flex;
    align-items: center;
    padding: 0.625em 1.875em;
    gap: 1.25em;
    width: 30.125em;
    height: 3.125em;
    box-shadow: 0.25em 0.25em 0.25em rgba(0, 0, 0, 0.25);
    border-radius: 0.625em;
    box-sizing: border-box;
}

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

.ID {
    width: 15%;
}

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

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

.MaintenanceType {
    width: 15%;
}

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

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


.State {
    width: 15%;
}

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

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

.CreationDate {
    width: 22.5%;
}

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

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

.CompletionDate {
    width: 22.5%;
}

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

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

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

.input {
    border: none;
}

#nuxt-link {
    text-decoration: none;
}

.nuxt-link-darkmode {
    color: white;
}

.nuxt-link-lightmode {
    color: #000;
}

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

.instanceLabel {
    width: 5.5625em;
    height: 1.875em;
    font-family: "Overpass";
    font-style: normal;
    font-weight: 400;
    font-size: 0.875em;
    line-height: 1.875;
    letter-spacing: 0.05em;
}

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

.section-lightmode {
    background-color: #fff;
}
</style>