import VueSelect from '/Components/Common/VueSelect.js?v=3.4'
import InputSearch from '/Components/Common/InputSearch.js?v=3.4'
import InputText from "/Components/Common/InputText.js?v=3.4"
import { getLabelText, getFileContentsFromInput } from '/Components/Common/utils.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"

export default {
    props: {
        addEditDTO: { type: Object, required: true },
        sdnServers: { type: Object, required: true },
        readOnly: { type: Boolean, required: true },
    },
    components: {
        VueSelect,
        InputSearch,
        InputText,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",

            recordDTO: this.addEditDTO,
            headerText: this.getLabelText('AddEditPublicIPs'),

            ddlSDNServers: this.sdnServers,
            ddlSDNInterfaces: {},

            fileXML: null,
        }
    },
    methods: {
        getLabelText,
        getFileContentsFromInput,
        listRecords: async function () {
            this.recordDTO = this.addEditDTO;

            this.recordDTO.SDNServerId = this.ddlSDNServers.items[0].value;
            this.recordDTO.SDNServerName = this.ddlSDNServers.items[0].text;
            //this.recordDTO.InterfaceId = this.ddlSDNInterfaces.items[0].value;
            //this.recordDTO.Interface = this.ddlSDNInterfaces.items[0].text;

            await this.listInterfaces();
        },
        sdnServersChangeHandler: async function (obj) {
            this.recordDTO.SDNServerId = obj.selectedValue;
            this.recordDTO.SDNServerName = obj.selectedText;

            clearAllMsgs();
            await this.listInterfaces();
        },
        sdnInterfacesChangeHandler: function (obj) {
            this.recordDTO.InterfaceId = obj.selectedValue;
            this.recordDTO.Interface = obj.selectedText;
        },
        listInterfaces: async function () {
            //console.log(this.recordDTO.SDNServerId);
            var vm = this;
            vm.ddlSDNInterfaces = {};

            await fetch("/PCC/VPS/SDN/AddEditPublicIP.aspx/GetSDNInterfaces?SDNServerId=" + vm.recordDTO.SDNServerId, fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.ddlSDNInterfaces = JSON.parse(data.d);
                    //vm.recordDTO.InterfaceId = vm.ddlSDNInterfaces.initialValue;
                    if (vm.ddlSDNInterfaces.items.length > 0) {
                        vm.recordDTO.InterfaceId = vm.ddlSDNInterfaces.items[0].value;
                        vm.recordDTO.Interface = vm.ddlSDNInterfaces.items[0].text;
                    }
                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        cancelRecord: function () {
            clearAllMsgs();

            this.recordDTO.IPAddressId = 0;

            window.location.href = '/PCC/VPS/SDN/SDN.aspx?TI=1';
        },
        saveRecord: async function (e) {
            clearAllMsgs();

            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

            if (disabledValue === 'true' || disabledValue === true)
                return false;

            this.isLoading = true;
            var fileName = '';
            var fileContent = '';

            if (!this.fileXML && this.recordDTO.IPAddress == '') {
                alert(this.getLabelText("FAM0038") + ' OR Specify any IP Address in text input.');
                this.isLoading = false;
                return false;
            }
            else if (this.fileXML) {
                fileName = this.fileXML.name;
                fileContent = await this.getFileContentsFromInput(this.fileXML);
                //console.log(fileContent);
            }

            if ((this.recordDTO.IPAddress == '' && fileContent == '') || this.recordDTO.Description == '' || this.recordDTO.SDNServerId <= 0 || this.recordDTO.InterfaceId <= 0) {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                this.isLoading = false;
                return false;
            }

            if (this.recordDTO.IPAddress != '') {
                // Validate comma-separated IPv4 addresses
                // Split, trim and remove empty entries
                const rawList = (this.recordDTO.IPAddress || '').split(',');
                const ips = rawList.map(s => s.trim()).filter(s => s.length > 0);

                if (ips.length === 0) {
                    displayErrorMsg(Error('No IP addresses provided.'));
                    this.isLoading = false;
                    return false;
                }

                const ipv4Regex = /^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/;

                const invalid = ips.filter(ip => !ipv4Regex.test(ip));

                if (invalid.length > 0) {
                    displayErrorMsg(Error('The following IP address(es) are invalid: ' + invalid.join(', ')));
                    this.isLoading = false;
                    return false;
                }
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'SDNPublicIPsDTO': this.recordDTO,
                'FileName': fileName,
                'FileContent': fileContent
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/SDN/AddEditPublicIP.aspx/SaveSDNPublicIPs", postRequest)
                .then(response => response.json()).then((data) => {

                    window.location.href = '/PCC/VPS/SDN/SDN.aspx?M=1&TI=1';
                }).catch(function (e) {
                    displayErrorMsg(e);
                });

            this.isLoading = false;
        },
        onFileChange: function (event) {
            this.fileXML = event.target.files[0];
        },
    },
    created: async function () {

        var vm = this;

        await this.listRecords().catch(function (e) {

            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    updated: function () {
        updateSelectInterface();
        AdminBSBThemeChanges();
    },
    template: '#addeditsdnpublicippool-template',
}
