<template>
    <section :class="['userAccount', loggedInUserDarkModeBoolean ? 'section-darkmode' : 'section-lightmode']">
        <h2 :class="['heading', loggedInUserDarkModeBoolean ? 'heading-darkmode' : 'heading-lightmode']">Account:</h2>
        <div class="userData">
            <div class="username-email">
                <div class="data-field" id="username">
                    <pre
                        :class="['label', loggedInUserDarkModeBoolean ? 'pre-darkmode' : 'pre-lightmode']">Username:</pre>
                    <pre v-if="!editable"
                        :class="['data', loggedInUserDarkModeBoolean ? 'data-darkmode' : 'data-lightmode']">{{ loggedInUserUsername }}</pre>
                    <input v-if="editable" v-model="loggedInUserUsername" @change="updateUsername()"
                        :class="['data', 'input', loggedInUserDarkModeBoolean ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="email">
                    <pre :class="['label', loggedInUserDarkModeBoolean ? 'pre-darkmode' : 'pre-lightmode']">Email:</pre>
                    <pre v-if="!editable"
                        :class="['data', loggedInUserDarkModeBoolean ? 'data-darkmode' : 'data-lightmode']">{{ loggedInUserEmail }}</pre>
                    <input v-if="editable" v-model="loggedInUserEmail" @change="updateUser()"
                        :class="['data', 'input', loggedInUserDarkModeBoolean ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <input v-if="editable"
                    :class="[loggedInUserDarkModeBoolean ? 'input-darkmode' : '', !loggedInUserDarkModeBoolean ? 'input-lightmode' : '',]"
                    type="button" id="changePassword" value="Change Password" @click="changePassword">
            </div>
            <div v-if="changePasswordBool && editable" class="password">
                <div class="data-field" id="password">
                    <pre
                        :class="['label', loggedInUserDarkModeBoolean ? 'pre-darkmode' : 'pre-lightmode']">New Password:</pre>
                    <input v-if="editable" v-model="loggedInUserNewPassword"
                        :class="['data', 'input', loggedInUserDarkModeBoolean ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="passwordRepeated">
                    <pre
                        :class="['label', loggedInUserDarkModeBoolean ? 'pre-darkmode' : 'pre-lightmode']">Repeat:</pre>
                    <input v-if="editable" v-model="loggedInUserNewPasswordRepeated"
                        :class="['data', 'input', loggedInUserDarkModeBoolean ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <input
                    :class="[loggedInUserDarkModeBoolean ? 'input-darkmode' : '', !loggedInUserDarkModeBoolean ? 'input-lightmode' : '',]"
                    type="button" id="savePassword" value="Save Password" @click="savePassword">
            </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.editableUser);
const changePasswordBool = ref(false);

const loggedInUserId = ref('');
const loggedInUserUsername = ref('');
const loggedInUserRegistered = ref('');
const loggedInUserLastLogin = ref('');
const loggedInUserFullName = ref('');
const loggedInUserEmail = ref('');
const loggedInUserPhonenumber = ref('');
const loggedInUserAddress = ref('');
const loggedInUserCity = ref('');
const loggedInUserPostcode = ref('');
const loggedInUserAdminBool = ref('');
const loggedInUserTechnicianBool = ref('');
const loggedInUserReaderBool = ref('');
const loggedInUserNewPassword = ref('');
const loggedInUserNewPasswordRepeated = ref('');
const loggedInUserDarkModeBool = ref('');
const loggedInUserDarkModeBoolean = ref('');
const employees = ref([]);

const changePassword = () => {
    changePasswordBool.value = !changePasswordBool.value
    loggedInUserNewPassword.value = '';
    loggedInUserNewPasswordRepeated.value = '';
}

const savePassword = async () => {
    // hier weiter machen
    if (loggedInUserNewPassword.value.length < 8) {
        alert("Please choose a password with minimal eight characters!");
        return
    }
    // password (repeat) must match
    if (loggedInUserNewPassword.value != loggedInUserNewPasswordRepeated.value) {
        alert("Your passwords don't match.");
        return
    }
    try {
        await Axios.put(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/updatePasswordEmployee`,
            {
                id: loggedInUserId.value,
                password: loggedInUserNewPassword.value,
            }
        )
        alert("Password successfully updatet!");
        changePasswordBool.value = false;
        loggedInUserNewPassword.value = '';
        loggedInUserNewPasswordRepeated.value = '';
    } catch (err) {
        console.log(err);
    };
}

const getSession = async () => {
    loggedInUserId.value = getItem('logged-in-user-id');
    loggedInUserUsername.value = getItem('logged-in-user-username');
    loggedInUserRegistered.value = getItem('logged-in-user-registered');
    loggedInUserLastLogin.value = getItem('logged-in-user-lastLogin');
    loggedInUserFullName.value = getItem('logged-in-user-fullName');
    loggedInUserEmail.value = getItem('logged-in-user-email');
    loggedInUserPhonenumber.value = getItem('logged-in-user-phonenumber');
    loggedInUserAddress.value = getItem('logged-in-user-address');
    loggedInUserCity.value = getItem('logged-in-user-city');
    loggedInUserPostcode.value = getItem('logged-in-user-postcode');
    loggedInUserAdminBool.value = getItem('logged-in-user-adminBool');
    loggedInUserTechnicianBool.value = getItem('logged-in-user-technicianBool');
    loggedInUserReaderBool.value = getItem('logged-in-user-readerBool');
    loggedInUserDarkModeBool.value = getItem('logged-in-user-darkMode');
    if (loggedInUserDarkModeBool.value == 1) {
        loggedInUserDarkModeBoolean.value = true;
    } else {
        loggedInUserDarkModeBoolean.value = false;
    }
}

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

const updateUsername = async () => {
    if (loggedInUserUsername.value.length < 5) {
        alert("Your username must have at least five characters!");
        loggedInUserUsername.value = getItem('logged-in-user-username');
        return;
    }
    var counter = 0;
    // check if the username already exists
    employees.value.forEach(empl => {
        if (empl.username === loggedInUserUsername.value) {
            counter += 1;
        }
    });
    if (counter == 1) {
        alert("This username already exists. Please choose an unique username!");
        loggedInUserUsername.value = getItem('logged-in-user-username');
        return;
    }
    await updateUser();
}

//update data
const updateUser = async () => {
    if (!validateEMail(loggedInUserEmail.value)) {
        alert("Please add a valid email!");
        loggedInUserEmail.value = getItem('logged-in-user-email');
        return;
    }
    if ((loggedInUserPhonenumber.value.length === 0) && (loggedInUserEmail.value.length === 0)) {
        alert("Please add a phonenumber or an email!");
        loggedInUserPhonenumber.value = getItem('logged-in-user-phonenumber');
        loggedInUserEmail.value = getItem('logged-in-user-email')
        return;
    }
    try {
        await Axios.put(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateEmployee`,
            {
                id: loggedInUserId.value,
                username: loggedInUserUsername.value,
                fullName: loggedInUserFullName.value,
                email: loggedInUserEmail.value,
                phonenumber: loggedInUserPhonenumber.value,
                address: loggedInUserAddress.value,
                city: loggedInUserCity.value,
                postcode: loggedInUserPostcode.value,
                adminBool: loggedInUserAdminBool.value,
                technicianBool: loggedInUserTechnicianBool.value,
                readerBool: loggedInUserReaderBool.value,
                darkModeBool: loggedInUserDarkModeBoolean.value,
            }
        )
        setItem('logged-in-user-username', loggedInUserUsername.value)
        setItem('logged-in-user-fullName', loggedInUserFullName.value)
        setItem('logged-in-user-email', loggedInUserEmail.value)
        setItem('logged-in-user-phonenumber', loggedInUserPhonenumber.value)
        setItem('logged-in-user-address', loggedInUserAddress.value)
        setItem('logged-in-user-city', loggedInUserCity.value)
        setItem('logged-in-user-postcode', loggedInUserPostcode.value)
        if (loggedInUserDarkModeBoolean.value) {
            loggedInUserDarkModeBool.value = 1;
        } else {
            loggedInUserDarkModeBool.value = 0;
        }
        setItem('logged-in-user-darkMode', loggedInUserDarkModeBool.value)
        getSession();
        store.commit('setLocalStorageChanged');
        store.commit('toggleUpdateDarkMode');
    } catch (err) {
        console.log(err.response.statusText);
    }
}

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

function setItem(item, value) {
    if (process.client) {
        localStorage.setItem(item, value)
        return true
    } else {
        return false
    }
}

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

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

watch(modeChanged, getSession)

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

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


<style scoped>
.userAccount {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    align-self: stretch;
    width: 100%;
    padding-left: 1.875rem;
    padding-right: 1.875rem;
    padding-top: 1.875rem;
    padding-bottom: 1.875rem;
    gap: 0.625rem;
    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;
}

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

input#changePassword:hover,
input#savePassword:hover {
    background-color: #454545;
}

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

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

.data-lightmode {
    background-color: #EBEBEB;
    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;
}

.input {
    border: none;
}

.heading {
    letter-spacing: 5%;
    font: 400 1rem/2rem Overpass, sans-serif;
}

.heading-darkmode {
    color: #fff;
}

.heading-lightmode {
    color: #000;
}

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

.userData {
    display: flex;
    flex-direction: row;
    align-content: center;
    gap: 0.625rem
}

.rectangle-container {
    display: flex;
}

.rectangle {
    width: 6.25em;
    height: 6.25em;
    flex: none;
    order: 0;
    flex-grow: 0;
}

.rectangle-darkmode {
    background-color: #212121;
}

.rectangle-lightmode {
    background-color: #EBEBEB;
}

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

.pre-darkmode {
    color: #fff;
}

.pre-lightmode {
    color: #000;
}

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

.data-lightmode {
    background-color: #EBEBEB;
    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;
    width: 12.5em;
}

.label {
    width: 6.25rem;
}

input#changePassword,
input#savePassword {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 10rem;
    height: 2.5rem;
    margin-top: 1rem;
    border-radius: 0.625rem;
    border: none;
    text-align: center;
    letter-spacing: 5%;
    font: 400 0.875rem/2rem Overpass, sans-serif;
    margin-right: 1.25rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}
</style>