<template>
    <section v-if="!addBool" :class="['group-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']" id="group">Groups:</div>
        <div class="asset-data">
            <div class="checkbox-container">
                <div class="checkbox-group">
                    <label :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']" for="admin-checkbox">Admin</label>
                    <input :readonly="!editable" id="admin-checkbox" type="checkbox" v-model="adminBoolean"
                        @click="toggleAdminBool()">
                </div>
                <div class="checkbox-group">
                    <label :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']" for="technician-checkbox">Technician</label>
                    <input :readonly="!editable" id="technician-checkbox" type="checkbox"
                        v-model="technicianBoolean" @click="toggleTechnicianBool()">
                </div>
                <div class="checkbox-group">
                    <label :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']" for="reader-checkbox">Reader</label>
                    <input :readonly="!editable" id="reader-checkbox" type="checkbox" v-model="readerBoolean"
                        @click="toggleReaderBool()">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addBool" :class="['group-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']" id="group">Groups:</div>
        <div class="asset-data">
            <div class="checkbox-container">
                <div class="checkbox-group">
                    <label :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']" for="admin-checkbox">Admin</label>
                    <input id="admin-checkbox" type="checkbox" v-model="newAdminBool">
                </div>
                <div class="checkbox-group">
                    <label :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']" for="technician-checkbox">Technician</label>
                    <input id="technician-checkbox" type="checkbox" v-model="newTechnicianBool">
                </div>
                <div class="checkbox-group">
                    <label :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']" for="reader-checkbox">Reader</label>
                    <input id="reader-checkbox" type="checkbox" v-model="newReaderBool">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addBool" id="saveNewEmployee">
        <button :class="[darkMode ? 'saveNewEmployee-darkmode' : 'saveNewEmployee-lightmode']"
            @click="addEmployee()">Save</button>
    </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 addBool = computed(() => store.state.new);
const newUsernameEmp = computed(() => store.state.newUsernameEmp);
const newPasswordEmp = computed(() => store.state.newPasswordEmp);
const newPasswordRepeatedEmp = computed(() => store.state.newPasswordRepeatedEmp);
const newFullNameEmp = computed(() => store.state.newFullNameEmp);
const newEmailEmp = computed(() => store.state.newEmailEmp);
const newPhonenumberEmp = computed(() => store.state.newPhonenumberEmp);
const newAddressEmp = computed(() => store.state.newAddressEmp);
const newCityEmp = computed(() => store.state.newCityEmp);
const newPostcodeEmp = computed(() => store.state.newPostcodeEmp);

const darkMode = ref('')
const employee = ref({});
const adminBoolean = ref(false);
const technicianBoolean = ref(false);
const readerBoolean = ref(false);
const newAdminBool = ref(false);
const newTechnicianBool = ref(false);
const newReaderBool = ref(false);
const newDarkModeBool = ref(false);
const employees = 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;
            if (employee.value.adminBool == 1) {
                adminBoolean.value = true;
            };
            if (employee.value.technicianBool == 1) {
                technicianBoolean.value = true;
            };
            if (employee.value.readerBool == 1) {
                readerBoolean.value = true;
            };
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

const toggleTechnicianBool = () => {
    technicianBoolean.value = !technicianBoolean.value;
    update();
}

const toggleAdminBool = () => {
    adminBoolean.value = !adminBoolean.value;
    update();
}

const toggleReaderBool = () => {
    readerBoolean.value = !readerBoolean.value;
    update();
}

//update data
const update = async () => {
    if (adminBoolean.value) {
        employee.value.adminBool = 1;
    } else {
        employee.value.adminBool = 0;
    }
    if (technicianBoolean.value) {
        employee.value.technicianBool = 1;
    } else {
        employee.value.technicianBool = 0;
    }
    if (readerBoolean.value) {
        employee.value.readerBool = 1;
    } else {
        employee.value.readerBool = 0;
    }
    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,
                darkModeBool: employee.value.darkModeBool,
            }
        );
    } catch (err) {
        console.log(err.response.statusText);
    }
    await getEmployeeById();
}

// add new employee
const addEmployee = async () => {
    // check if all input data is valid
    if (newUsernameEmp.value.trim() === "") {
        alert("Please add an username!");
        return;
    } else {
        var counter = 0;
        // check if the username already exists
        employees.value.forEach(empl => {
            if (empl.username === newUsernameEmp.value) {
                counter += 1;
            }
        });
        if (counter == 1) {
            alert("This username already exists. Please choose an unique username or modify respectively delete the old one!");
            return;
        }
    }
    if (newPasswordEmp.value.trim() === "") {
        alert("Please add a password!");
        return;
    }
    // username min length 5
    if (!newUsernameEmp.value || newUsernameEmp.value.length < 5) {
        alert("Please choose an username with minimal five characters!");
        return
    }
    // password min 8 chars
    if (!newPasswordEmp.value || newPasswordEmp.value.length < 8) {
        alert("Please choose a password with minimal eight characters!");
        return
    }
    // password (repeat) must match
    if (
        !newPasswordRepeatedEmp.value ||
        newPasswordEmp.value != newPasswordRepeatedEmp.value
    ) {
        alert("Your passwords don't match.");
        return
    }
    if (newFullNameEmp.value.length === 0) {
        alert("Please add a name!");
        return;
    }
    if (newCityEmp.value.length === 0) {
        alert("Please add a city!");
        return;
    }
    if (newAddressEmp.value.length === 0) {
        alert("Please add an address!");
        return;
    }
    if (!validateEMail(newEmailEmp.value)) {
        alert("Please add a valid email!");
        return;
    }
    if (!validatePhonenumber(newPhonenumberEmp.value)) {
        alert("Please add a valid phonenumber!");
        return;
    }
    if (!validatePostcode(newPostcodeEmp.value)) {
        alert("Please add a valid postcode!");
        return;
    }
    if ((newPhonenumberEmp.value.length === 0) && (newEmailEmp.value.length === 0)) {
        alert("Please add a phonenumber or an email!");
        return;
    }
    if (! (newAdminBool.value || newTechnicianBool.value || newReaderBool.value)) {
        alert("Please choose at least one group!");
        return;
    }
    try {
        let res = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/signup`,
            {
                username: newUsernameEmp.value,
                password: newPasswordEmp.value,
                password_repeat: newPasswordRepeatedEmp.value,
                fullName: newFullNameEmp.value,
                email: newEmailEmp.value,
                phonenumber: newPhonenumberEmp.value,
                address: newAddressEmp.value,
                city: newCityEmp.value,
                postcode: newPostcodeEmp.value,
                adminBool: newAdminBool.value,
                technicianBool: newTechnicianBool.value,
                readerBool: newReaderBool.value,
                darkModeBool: newDarkModeBool.value,
            });
        store.commit('resetStore');
        store.commit('changeToEmployeelist');
    } catch (err) {
        console.log(err.response.statusText);
    }
}

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

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

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

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(() => {
    getSession();
    triggerBackendCallsWithDelay(getEmployeeById);
    triggerBackendCallsWithDelay(getEmployees);
});
</script>

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


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

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

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

.div-darkmode {
    color: #fff;
}

.div-lightmode {
    color: #000;
}

.label#network {
    padding-top: 1rem;
    padding-bottom: 1rem;
}

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

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

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

.saveNewEmployee-darkmode {
    background: #2c2c2c;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 1rem 1.875rem;
    width: 8%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.saveNewEmployee-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 1rem 1.875rem;
    width: 8%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.saveNewEmployee-darkmode:hover {
    background-color: #444444;
    cursor: pointer;
}

.saveNewEmployee-lightmode:hover {
    background-color: #ACACAC;
    cursor: pointer;
}

#saveNewEmployee {
    text-align: center;
}

.input {
    border: none;
}

.checkbox-container {
    padding-bottom: 0.8rem;
    display: flex;
    justify-content: center;
}

.checkbox-group {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 20rem;
}

.checkbox-group label {
    margin-bottom: 5px;
}

.checkbox-group input {
    margin-bottom: 10px;
}

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

.pre-darkmode {
    color: #fff;
}

.pre-lightmode {
    color: #000;
}

input[type=checkbox]{
  accent-color:  #000;  
  }
</style>