<template>
    <section v-if="networkBoolean && !addAssetBool"
        :class="['network-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']" id="network">Network specifications:</div>
        <div class="asset-data">
            <div class="IPv4-MAC">
                <div class="data-field" id="IPv4">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">IPv4:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ inputIPv4 }}</pre>
                    <input v-if="editable" v-model="inputIPv4" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="MAC">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">MAC:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ item.MAC }}</pre>
                    <input v-if="editable" v-model="item.MAC" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
            <div class="IPv6-subnetmask">
                <div class="data-field" id="IPv6">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">IPv6:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ inputIPv6 }}</pre>
                    <input v-if="editable" v-model="inputIPv6" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="subnetmask">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">Subnetmask:</pre>
                    <pre v-if="!editable"
                        :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ item.subnetmask }}</pre>
                    <input v-if="editable" v-model="item.subnetmask" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addAssetBool" :class="['network-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']" id="network">Network specifications:</div>
        <div class="asset-data">
            <div class="IPv4-MAC">
                <div class="data-field" id="IPv4">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">IPv4:</pre>
                    <input v-model="newIPv4" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="MAC">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">MAC:</pre>
                    <input v-model="newMAC" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
            <div class="IPv6-subnetmask">
                <div class="data-field" id="IPv6">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">IPv6:</pre>
                    <input v-model="newIPv6" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
                <div class="data-field" id="subnetmask">
                    <pre :class="['label', darkMode ? 'div-darkmode' : 'div-lightmode']">Subnetmask:</pre>
                    <input v-model="newSubnetmask" @change="updateConfigItem()"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </div>
            </div>
        </div>
    </section>
    <section v-if="addAssetBool" id="saveNewItem">
        <button :class="[darkMode ? 'saveNewItem-darkmode' : 'saveNewItem-lightmode']" @click="addItem()">Safe</button>
    </section>
</template>
    

<script setup>
import { ref, onMounted } 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.assetEditable);
const chosenAssetId = computed(() => store.state.chosenAssetId);
const addAssetBool = computed(() => store.state.newAsset);
const newAssetName = computed(() => store.state.newAssetName);
const newCustomerID = computed(() => store.state.newCustomerID);
const newCustomer = computed(() => store.state.newCustomer);
const newLocation = computed(() => store.state.newLocation);
const newRemoteLocation = computed(() => store.state.newRemoteLocation);
const newType = computed(() => store.state.newType);
const newDescription = computed(() => store.state.newDescription);
const newNotes = computed(() => store.state.newNotes);
const newState = computed(() => store.state.newState);
const newLastView = computed(() => store.state.newLastView);
const newUser = computed(() => store.state.newUser);
const hardwareBool = computed(() => store.state.hardwareBool);
const newModel = computed(() => store.state.newModel);
const newSerialnumber = computed(() => store.state.newSerialnumber);
const newCPU = computed(() => store.state.newCPU);
const newRAM = computed(() => store.state.newRAM);
const newStorageConfiguration = computed(() => store.state.newStorageConfiguration);
const newMiscellaneous = computed(() => store.state.newMiscellaneous);
const softwareBool = computed(() => store.state.softwareBool);
const newSoftware = computed(() => store.state.newSoftware);
const newVersion = computed(() => store.state.newVersion);
const newLicense = computed(() => store.state.newLicense);

const darkMode = ref(true)
const item = ref({});
const networkBoolean = ref(false);
const inputIPv4 = ref('');
const inputIPv6 = ref('');
const newNetworkBool = ref(true);
const newIPv4 = ref('');
const newIPv6 = ref('');
const newMAC = ref('');
const newSubnetmask = ref('');
const configItems = ref([]);

// get config item from id
const getItemById = async () => {
    if (!addAssetBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getConfigItem/${chosenAssetId.value}`
            );
            item.value = response.data;
            if (item.value.networkBool == 1) {
                networkBoolean.value = true;
            };
            if (item.value.IPv4 == null) {
                inputIPv4.value = "";
            } else {
                inputIPv4.value = item.value.IPv4;
            }
            if (item.value.IPv6 == null) {
                inputIPv6.value = "";
            } else {
                inputIPv6.value = item.value.IPv6;
            }
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

// helper function to validate an IPv4 address
const validateIPv4address = (ipaddress) => {
    const ipv4format = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    if (ipv4format.test(ipaddress) || ipaddress === "") {
        return true;
    } else {
        return false;
    }
}

// helper function to validate an IPv4 address
const validateIPv6address = (ipaddress) => {
    const ipv6format = /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/gi;
    if (ipv6format.test(ipaddress) || ipaddress === "") {
        return true;
    } else {
        return false;
    }
}

//update data
const updateConfigItem = async () => {
    if (inputIPv4.value.length === 0 && inputIPv6.value.length === 0 && item.value.MAC.length === 0 && item.value.subnetmask.length === 0) {
        item.value.networkBool = 0;
    }
    if (validateIPv4address(inputIPv4.value)) {
        item.value.IPv4 = inputIPv4.value;
        try {
            await Axios.put(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateConfigItem`,
                {
                    primaryID: item.value.primaryID,
                    assetName: item.value.assetName,
                    customerID: item.value.customerID,
                    customer: item.value.customer,
                    location: item.value.location,
                    remoteLocation: item.value.remoteLocation,
                    type: item.value.type,
                    description: item.value.description,
                    notes: item.value.notes,
                    state: item.value.state,
                    lastView: item.value.lastView,
                    user: item.value.user,
                    hardwareBool: item.value.hardwareBool,
                    model: item.value.model,
                    serialnumber: item.value.serialnumber,
                    CPU: item.value.CPU,
                    RAM: item.value.RAM,
                    storageConfiguration: item.value.storageConfiguration,
                    miscellaneous: item.value.miscellaneous,
                    softwareBool: item.value.softwareBool,
                    software: item.value.software,
                    version: item.value.version,
                    license: item.value.license,
                    networkBool: item.value.networkBool,
                    IPv4: item.value.IPv4,
                    IPv6: item.value.IPv6,
                    MAC: item.value.MAC,
                    subnetmask: item.value.subnetmask,
                }
            );
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        if (item.value.IPv4 == null) {
            inputIPv4.value = "";
        } else {
            inputIPv4.value = item.value.IPv4;
        }
        alert("You have entered an invalid IPv4 address, please choose a valid one!");
    }
    if (validateIPv6address(inputIPv6.value)) {
        item.value.IPv6 = inputIPv6.value;
        try {
            await Axios.put(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateConfigItem`,
                {
                    primaryID: item.value.primaryID,
                    assetName: item.value.assetName,
                    customerID: item.value.customerID,
                    customer: item.value.customer,
                    location: item.value.location,
                    remoteLocation: item.value.remoteLocation,
                    type: item.value.type,
                    description: item.value.description,
                    notes: item.value.notes,
                    state: item.value.state,
                    lastView: item.value.lastView,
                    user: item.value.user,
                    hardwareBool: item.value.hardwareBool,
                    model: item.value.model,
                    serialnumber: item.value.serialnumber,
                    CPU: item.value.CPU,
                    RAM: item.value.RAM,
                    storageConfiguration: item.value.storageConfiguration,
                    miscellaneous: item.value.miscellaneous,
                    softwareBool: item.value.softwareBool,
                    software: item.value.software,
                    version: item.value.version,
                    license: item.value.license,
                    networkBool: item.value.networkBool,
                    IPv4: item.value.IPv4,
                    IPv6: item.value.IPv6,
                    MAC: item.value.MAC,
                    subnetmask: item.value.subnetmask,
                }
            );
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        if (item.value.IPv6 == null) {
            inputIPv6.value = "";
        } else {
            inputIPv6.value = item.value.IPv6;
        }
        alert("You have entered an invalid IPv6 address, please choose a valid one!");
    }
    await getItemById();
}

// add new config item
const addItem = async () => {
    if (newIPv4.value.length === 0 && newIPv6.value.length === 0 && newMAC.value.length === 0 && newSubnetmask.value.length === 0) {
        newNetworkBool.value = false;
    }
    // check if all input data is valid
    if (newAssetName.value.trim() === "") {
        alert("Please add a config item name!");
        return;
    } else {
        var counter = 0;
        // check if config item name already exists
        configItems.value.forEach(ci => {
            if (ci.assetName === newAssetName.value) {
                counter += 1;
            }
        });
        if (counter == 1) {
            alert("This asset name already exists. Please choose an unique asset name or modify respectively delete the old one!");
            return;
        }
    }
    if (newCustomer.value.length === 0) {
        alert("Please choose a client!");
        return;
    }
    if (!validateIPv4address(newIPv4.value)) {
        alert("Please enter a valid IPv4 address or leave this field empty!");
        return;
    }
    if (!validateIPv6address(newIPv6.value)) {
        alert("Please enter a valid IPv6 address or leave this field empty!");
        return;
    }
    try {
        const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addConfigItem`,
            {
                assetName: newAssetName.value,
                customerID: newCustomerID.value,
                customer: newCustomer.value,
                location: newLocation.value,
                remoteLocation: newRemoteLocation.value,
                type: newType.value,
                description: newDescription.value,
                notes: newNotes.value,
                state: newState.value,
                lastView: newLastView.value,
                user: newUser.value,
                hardwareBool: hardwareBool.value,
                model: newModel.value,
                serialnumber: newSerialnumber.value,
                CPU: newCPU.value,
                RAM: newRAM.value,
                storageConfiguration: newStorageConfiguration.value,
                miscellaneous: newMiscellaneous.value,
                softwareBool: softwareBool.value,
                software: newSoftware.value,
                version: newVersion.value,
                license: newLicense.value,
                networkBool: newNetworkBool.value,
                IPv4: newIPv4.value,
                IPv6: newIPv6.value,
                MAC: newMAC.value,
                subnetmask: newSubnetmask.value,
            });
        store.commit('resetAssetStore');
        store.commit('changeToAssetlist');
    } catch (err) {
        console.log(err.response.statusText);
    }
}

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

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

onMounted(() => {
    triggerBackendCallsWithDelay(getItemById);
    triggerBackendCallsWithDelay(getConfigItems);
});
</script>

<script>
export default {
    name: "NetworkSpecifications",
};
</script>          
      
      
<style scoped>
.network-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 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;
}

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

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

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

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

#saveNewItem {
    text-align: center;
}

.input {
    border: none;
}
</style>