<template>
    <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <h2 v-if="!editable" :class="['employee-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{
        employee.fullName }}</h2>
        <input v-if="editable" v-model="employee.fullName" @change="updateEmpl()"
            :class="['data', 'employee-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="employee-data">
            <div class="username-registered-lastLogin">
                <div class="data-field" id="username">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Username:</pre>
                    <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"> {{ employee.username }}</pre>
                </div>
                <div class="data-field" id="registered">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Registered:</pre>
                    <pre
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"> {{ employee.registered }}</pre>
                </div>
                <div class="data-field" id="lastLogin">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Last login:</pre>
                    <pre
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"> {{ employee.lastLogin }}</pre>
                </div>
            </div>
            <div class="info">
                <div class="city-phonenumber">
                    <div class="data-field" id="city">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">City:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ employee.city }}</pre>
                        <input v-if="editable" v-model="employee.city" @change="updateEmpl()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="data-field" id="phonenumber">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Phonenumber:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ employee.phonenumber }}</pre>
                        <input v-if="editable" v-model="employee.phonenumber" @change="updateEmpl()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
                <div class="postcode-email">
                    <div class="data-field" id="postcode">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Postcode:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ employee.postcode }}</pre>
                        <input v-if="editable" v-model="employee.postcode" @change="updateEmpl()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="data-field" id="email">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Email:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ employee.email }}</pre>
                        <input v-if="editable" v-model="employee.email" @change="updateEmpl()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
                <div class="address">
                    <div class="data-field" id="address">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Address:</pre>
                        <pre v-if="!editable"
                            :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']"> {{ employee.address }}</pre>
                        <input v-if="editable" v-model="employee.address" @change="updateEmpl()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="data-field" id="empty">
                        &nbsp;
                    </div>
                </div>
            </div>
        </div>
    </section>
    <section v-if="addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <input v-model="newFullName" @change="updateEmployee()"
            :class="['data', 'employee-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
        <div class="employee-data">
            <div class="username-registered-lastLogin">
                <div class="data-field" id="username">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Username:</pre>
                    <input v-model="newUsername" @change="updateEmployee()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="password">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Password:</pre>
                    <input v-model="newPassword" @change="updateEmployee()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="passwordRepeated">
                    <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Password repeated:</pre>
                    <input v-model="newPasswordRepeated" @change="updateEmployee()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
            <div class="info">
                <div class="city-phonenumber">
                    <div class="data-field" id="city">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">City:</pre>
                        <input v-model="newCity" @change="updateEmployee()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="data-field" id="phonenumber">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Phonenumber:</pre>
                        <input v-model="newPhonenumber" @change="updateEmployee()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
                <div class="postcode-email">
                    <div class="data-field" id="postcode">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Postcode:</pre>
                        <input v-model="newPostcode" @change="updateEmployee()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="data-field" id="email">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Email:</pre>
                        <input v-model="newEmail" @change="updateEmployee()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                </div>
                <div class="address">
                    <div class="data-field" id="address">
                        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Address:</pre>
                        <input v-model="newAddress" @change="updateEmployee()"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </div>
                    <div class="data-field" id="empty">
                        &nbsp;
                    </div>
                </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 modeChanged = computed(() => store.state.updateDarkMode);

const editable = computed(() => store.state.editable);
const chosenEmployeeId = computed(() => store.state.chosenEmployeeId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);

const darkMode = ref('');
const employee = ref({});

const newUsername = ref('');
const newPassword = ref('');
const newPasswordRepeated = ref('');
const newFullName = ref('');
const newEmail = ref('');
const newPhonenumber = ref('');
const newAddress = ref('');
const newCity = ref('');
const newPostcode = ref('');

// get employee from id
const getEmployeeById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getEmployee/${chosenEmployeeId.value}`
            );
            employee.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// update employee fields in the store
const updateEmployee = () => {
    const employee = {
        username: newUsername.value,
        password: newPassword.value,
        passwordRepeated: newPasswordRepeated.value,
        fullName: newFullName.value,
        email: newEmail.value,
        phonenumber: newPhonenumber.value,
        address: newAddress.value,
        city: newCity.value,
        postcode: newPostcode.value
    };
    store.commit('updateEmployeeComponent', employee);
}

//update data
const updateEmpl = async () => {
    if (employee.value.fullName.trim() === "") {
        alert("Please add a name!");
        return;
    }
    if (employee.value.city.trim() === "") {
        alert("Please add a city!");
        return;
    }
    if (employee.value.address.trim() === "") {
        alert("Please add an address!");
        return;
    }
    if (!validateEMail(employee.value.email)) {
        alert("Please add a valid email!");
        return;
    }
    if (!validatePhonenumber(employee.value.phonenumber)) {
        alert("Please add a valid phonenumber!");
        return;
    }
    if (!validatePostcode(employee.value.postcode)) {
        alert("Please add a valid postcode!");
        return;
    }
    try {
        await Axios.put(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateEmployee`,
            {
                id: employee.value.id,
                username: employee.value.username,
                fullName: employee.value.fullName,
                email: employee.value.email,
                phonenumber: employee.value.phonenumber,
                address: employee.value.address,
                city: employee.value.city,
                postcode: employee.value.postcode,
                adminBool: employee.value.adminBool,
                technicianBool: employee.value.technicianBool,
                readerBool: employee.value.readerBool,
            }
        )
        await getEmployeeById();
    } catch (err) {
        console.log(err.response.statusText);
    }
}

const confirmDeleteEmployee = async () => {
    if (deleteBool.value === true) {
        if (confirm("Do you really want to delete this employee? It cannot be undone!")) {
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteEmployee/${chosenEmployeeId.value}`);
                store.commit('undoDelete');
                store.commit('resetStore');
                store.commit('changeToEmployeelist');
            } catch (err) {
                console.log(err.response.statusText);
            }
        } else {
            store.commit('undoDelete');
        }
    }
}

// to validate the email address
const validateEMail = (email) => {
    const emailRegex = new RegExp(/^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$/, "gm");
    if (email === "") {
        return true
    }
    return emailRegex.test(email);
}

// to validate the phonenumber
const validatePhonenumber = (number) => {
    const mobilephonenumberRegex = new RegExp(/^(((((00|\+){1,2})49([ \-/]?|[ \()/]?))|0)[1]([0-2]|[4-7])([0-9]{1})([ \-/]?|[ \()/]?)([0-9]{8}))$/, "gm");
    const landlineRegex = new RegExp(/^0(30|40|69|89|20[12389]|21[24]|228|234|335|340|3[3-9][15]|906|[2-9][1-9]1|3(?:3(?:[0237][127]|0[3-6]|2[89]|3[458]|[46][1246]|7[589]|8[1256]|9[145])|4(?:[2347][135]|[34]7|[69][146]|48|62|76|93)|5(?:[04679][14]|[238][135]|[2469]2|[4789]6|[278]8|63|73|37|29)|6(?:[024689][13]|[03789]5|06|2[2489]|3[1246]|44|47|7[1279]|82|86)|7(?:[236][135]|2[2467]|37|4[145]|62|64|7[1-4])|8(?:[234678]1|3[468]|4[347]|6[035-9]|7[467]|83|86)|9(?:[236][135]|[04689]4|[04789]1|[03468]7|02|09|28|4[369]|6[2689]|73|76|96|98))|3[3-9][0-9]{3}|13[078]|180[235]|18[01]|19[0-9]{3}|[789]00|[2-9][0-9]{3})([0-9]{1,})$/, "gm");
    if (number === "") {
        return true
    }
    if (mobilephonenumberRegex.test(number)) {
        return true
    } else if (landlineRegex.test(number)) {
        return true;
    }
    return false;
}

// to validate the postcode
const validatePostcode = (postcode) => {
    const postcodeRegex = new RegExp(/^\d{5}$/);
    if (postcode === "") {
        return true
    }
    return postcodeRegex.test(postcode);
}

watch(deleteBool, confirmDeleteEmployee);

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)

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

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


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


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

.employee-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: 100%;
    padding: 0.8rem 1.875rem;
    gap: 1.25rem;
    border-radius: 0.625rem;
}

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

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

.data-field#street-name {
    width: 70%;
}

.data-field#street-no {
    width: 30%;
}

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

.pre-darkmode {
    color: #fff;
}

.pre-lightmode {
    color: #000;
}

.input {
    border: none;
}

.data {
    display: flex;
    overflow-x: auto;
    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;
}

.data#notes,
.data#description {
    align-self: stretch;
    /* width: 45%; */
    scrollbar-width: none;
    overflow-x: auto;
}

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

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

.additional {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    line-height: normal;
    width: 50%;
    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;
}

.city-phonenumber,
.postcode-email {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-self: stretch;
    padding: 0 1.875rem 0 0;
    gap: 0.625rem;
}
</style>
