<template>
    <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <h2 v-if="!editable" :class="['production-orders-template-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{
            pot.name }}</h2>
        <input v-if="editable" v-model="pot.name" @change="updatePOT()"
            :class="['data', 'pot-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="production-orders-template-data">
            <div class="client-ID">
                <div class="data-field" id="client">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">Customer:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"> {{ pot.customer }}</pre>
                    <select v-if="editable" id="customersDropDownChosenCI" v-model="pot.customer"
                        @change="updateCustomerID()" :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                        <option v-for="cust in customers" :key="cust.primaryID">
                            {{ cust.customername }}
                        </option>
                    </select>
                </div>
                <div class="data-field" id="ID">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">ID:</pre>
                    <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ pot.templateID }}</pre>
                </div>
            </div>
            <div class="user">
                <div class="data-field" id="empty">
                    &nbsp;
                </div>
                <div class="data-field" id="user">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">User:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ pot.user }}</pre>
                    <input v-if="editable" v-model="pot.user" @change="updatePOT()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
        </div>
        <div class="production-orders-template-data">
            <div class="additional">
                <div class="description">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Description:</h3>
                    <input v-model="pot.description" :readonly="!editable" @change="updatePOT()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="description">
                </div>
            </div>
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="pot.notes" :readonly="!editable" @change="updatePOT()"
                        :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="updateProductionOrder()"
            :class="['data', 'production-orders-template-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="production-orders-template-data">
            <div class="client-ID">
                <div class="data-field" id="client">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
                    <select id="customersDropDownChosenCI" v-model="newCustomer" @change="updateNewCustomerID()"
                        :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                        <option v-for="cust in customers" :key="cust.primaryID">
                            {{ cust.customername }}
                        </option>
                    </select>
                </div>
                <div class="data-field" id="ID">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">ID:</pre>
                    <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
                </div>
            </div>
            <div class="user">
                <div class="data-field" id="empty">
                    &nbsp;
                </div>
                <div class="data-field" id="user">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">User:</pre>
                    <input v-model="newUser" @change="updateProductionOrder()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
        </div>
        <div class="production-orders-template-data">
            <div class="additional">
                <div class="description">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Description:</h3>
                    <input v-model="newDescription" @change="updateProductionOrder()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="description">
                </div>
            </div>
            <div class="additional">
                <div class="notes">
                    <h3 :class="['area-title', darkMode ? 'h3-darkmode' : 'h3-lightmode']">Notes:</h3>
                    <input v-model="newNotes" @change="updateProductionOrder()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="description">
                </div>
            </div>
        </div>
    </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 editable = computed(() => store.state.editable);
const chosenPOTId = computed(() => store.state.chosenPOTId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);

const darkMode = ref(true);
const pot = ref({});
const customers = ref([]);
const customer = ref({});
const productionOrderTemplates = ref([]);

const newName = ref('');
const newCustomerID = ref('');
const newCustomer = ref('');
const newUser = ref('');
const newDescription = ref('');
const newNotes = 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);
    }
}

const confirmDeletePOT = async () => {
    if (deleteBool.value === true) {
        if (confirm("Do you really want to delete this production order template? It cannot be undone!")) {
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteProductionOrderTemplate/${chosenPOTId.value}`);
                store.commit('undoDelete');
                store.commit('changeToTemplatelist');
            } catch (err) {
                console.log(err.response.statusText);
            }
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteTodosPOT/${chosenPOTId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
        } else {
            store.commit('undoDelete');
        }
    }
}

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

//update data
const updatePOT = async () => {
    if (pot.value.name.trim() === "") {
        alert("Please add a production order template name!");
        return;
    } else {
        var counter = 0;
        // check if production order template name already exists
        productionOrderTemplates.value.forEach(p => {
            if (p.name === pot.value.name) {
                counter += 1;
            }
        });
        if (counter == 2) {
            alert("This production order template name already exists. Please choose an unique production order template name or modify respectively delete the old one!");
            pot.value.name = '';
            return;
        }
        try {
            await Axios.put(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateProductionOrderTemplate`,
                {
                    templateID: pot.value.templateID,
                    name: pot.value.name,
                    customerID: pot.value.customerID,
                    customer: pot.value.customer,
                    lastView: pot.value.lastView,
                    user: pot.value.user,
                    description: pot.value.description,
                    notes: pot.value.notes,
                }
            )
            await getPOTById();
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// update customerid if customer was changed
const updateCustomerID = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustomerByName/${pot.value.customer}`);
        customer.value = response.data;
        pot.value.customerID = customer.value.customerID;
        store.commit('toggleClientChanged');
        store.commit('toggleClientId', pot.value.customerID);
    } catch (err) {
        console.log(err.response.statusText);
    }
    await updatePOT();
}

// get production order template from id
const getPOTById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getProductionOrderTemplate/${chosenPOTId.value}`
            );
            pot.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// update customerid if customer was changed
const updateNewCustomerID = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustomerByName/${newCustomer.value}`);
        newCustomerID.value = response.data.customerID;
        store.commit('toggleClientChanged');
        store.commit('toggleClientId', newCustomerID.value)
    } catch (err) {
        console.log(err.response.statusText);
    }
    updateProductionOrder();
}

// update production order template fields in the store
const updateProductionOrder = () => {
    const productionOrderTemplate = {
        name: newName.value,
        customerId: newCustomerID.value,
        customer: newCustomer.value,
        user: newUser.value,
        description: newDescription.value,
        notes: newNotes.value
    };
    store.commit('updateProductionOrderTemplateComponent', productionOrderTemplate);
}

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

watch(deleteBool, confirmDeletePOT);

onMounted(() => {
    getPOTById();
    getProductionOrderTemplates();
    triggerBackendCallsWithDelay(getCustomers);
});
</script>

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

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

.production-orders-template-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;
}

.production-orders-template-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;
}

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

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

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

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

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

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

.input {
    border: none;
}

.production-orders-template-data {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    align-self: stretch;
}

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

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

div#empty {
    height: 3.6rem;
}

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

.div-darkmode,
.h3-darkmode {
    color: #fff;
}

.h3-lightmode {
    color: #000;
}


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

.description,
.notes {
    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;
}
</style>