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

export default {
    props: {
        addEditDTO: { type: Object, required: true },
        readOnly: { type: Boolean, required: true },
        aliasTypesAddEdit: { type: Object, 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('AddAlias'),

            ddlCustomers: {},
            ddlSubs: {},
            headerTextType: '',
            typeHint: '',
            typeWiseInputLabel: '',
            typesFilter: this.aliasTypesAddEdit,
        }
    },
    methods: {
        getLabelText,
        inputSearchChangeHandler: function (obj) {
            let index = obj.id.toString().split("_")[1];
            this.recordDTO.Details[index].Description = obj.searchValue;
        },
        inputAliasNameChangeHandler: function (obj) {
            //this.recordDTO.AliasName = obj.searchValue;

            //**** Alias name cannot be changed in edit mode, append CustomerId in add case only. ****//
            //if (this.recordDTO.AliasId <= 0) {
            var incoming = (obj.searchValue || '').toString().trim();

            // If incoming already starts with the customer id, keep as-is; otherwise prepend
            if (incoming.startsWith(this.recordDTO.CustomerId.toString() + '_')) {
                this.recordDTO.AliasName = incoming;
            }
            else {
                this.recordDTO.AliasName = this.recordDTO.CustomerId.toString() + '_' + incoming;
            }
            //}            
        },
        listRecords: async function () {
            if (this.recordDTO.AliasId > 0) {
                this.headerText = this.getLabelText('EditAlias');
                //await this.getRecordToEdit();

                if (this.recordDTO.IsDefault)
                    this.headerText = this.getLabelText('AliasDetail');
            }
            else {
                this.recordDTO = this.addEditDTO;
                //this.recordDTO.CustomerId = this.ddlCustomers.items[0].value;
                //this.recordDTO.CustomerName = this.ddlCustomers.items[0].text;
                //this.recordDTO.AliasType = 'host';
                this.recordDTO.AliasName = this.recordDTO.CustomerId.toString() + '_';

                this.addMoreItemDetail();

                this.headerText = this.getLabelText('AddAlias');
            }

            await this.fillSubs();
            this.setHeaderTextType();
        },
        customerChangeHandler: async function (obj) {
            this.recordDTO.CustomerId = obj.selectedValue;
            this.recordDTO.CustomerName = obj.selectedText;
            this.recordDTO.AliasName = this.recordDTO.CustomerId.toString() + '_';

            await this.fillSubs();
        },
        subsChangeHandler: function (obj) {
            this.recordDTO.SDNServerId = obj.selectedValue;
        },
        aliasTypeChangeHandler: function (obj) {
            this.recordDTO.AliasType = obj.selectedValue;

            this.setHeaderTextType();
        },
        setHeaderTextType: function () {
            //***** Reset details array if type is changed durring add operation *****/
            if (this.recordDTO.AliasId <= 0)
                this.recordDTO.Details = [{ "AliasDetailId": 0, "IPOrNetworkOrFQDN": "", "SubnetOrDays": 32, "Description": "" }];

            if (this.recordDTO.AliasType == 'host') {
                this.headerTextType = 'Host(s)';
                this.typeHint = this.getLabelText('HostsHint');
                this.typeWiseInputLabel = this.getLabelText('IPOrFQDN');
            }
            else if (this.recordDTO.AliasType == 'network') {
                this.headerTextType = 'Networks(s)';
                this.typeHint = this.getLabelText('NetworksHint');
                this.typeWiseInputLabel = this.getLabelText('NetworkOrFQDN');
            }
            else if (this.recordDTO.AliasType == 'port') {
                this.headerTextType = 'Port(s)';
                this.typeHint = this.getLabelText('PortsHint');
                this.typeWiseInputLabel = this.getLabelText('GN0000565');
            }
            else if (this.recordDTO.AliasType == 'urlips') {
                this.headerTextType = 'URL IP(s)';
                this.typeHint = this.getLabelText('URLIPsHint');
                this.typeWiseInputLabel = this.getLabelText('URLIPs');
            }
            else if (this.recordDTO.AliasType == 'urlports') {
                this.headerTextType = 'URL Ports(s)';
                this.typeHint = this.getLabelText('URLPortsHint');
                this.typeWiseInputLabel = this.getLabelText('URLPorts');
            }
            else if (this.recordDTO.AliasType == 'urltableips') {
                this.headerTextType = 'URL Table IP(s)';
                this.typeHint = this.getLabelText('URLTableIPsHint');
                this.typeWiseInputLabel = this.getLabelText('URLTableIPs');
            }
            else if (this.recordDTO.AliasType == 'urltableports') {
                this.headerTextType = 'URL Table Port(s)';
                this.typeHint = this.getLabelText('URLTablePortsHint');
                this.typeWiseInputLabel = this.getLabelText('URLTablePorts');
            }
        },
        removeInputDetail: function (indx) {
            this.recordDTO.Details.splice(indx, 1);
        },
        addMoreItemDetail: function () {
            this.recordDTO.Details.push({ "AliasDetailId": 0, "IPOrNetworkOrFQDN": "", "SubnetOrDays": 32, "Description": "" });
        },
        fillSubs: async function () {
            var vm = this;

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

                    vm.ddlSubs = JSON.parse(data.d);

                    if (vm.ddlSubs.items.length > 0) {

                        //**** Avoid to set default value when in edit mode ****//
                        if (vm.recordDTO.AliasId <= 0)
                            vm.recordDTO.SDNServerId = vm.ddlSubs.items[0].value;

                        if (vm.ddlSubs.items.length == 1) {
                            vm.ddlSubs.show = false;
                        }
                    }
                });
        },
        fillCustomers: async function () {
            var vm = this;

            await fetch("/PCC/VPS/SDN/AddEditAlias.aspx/FillCustomers", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.ddlCustomers = JSON.parse(data.d);

                    //**** Avoid to set default value when in edit mode ****//
                    if (vm.ddlCustomers.items.length > 0 && vm.recordDTO.AliasId <= 0) {
                        vm.recordDTO.CustomerId = vm.ddlCustomers.items[0].value;
                        vm.recordDTO.CustomerName = vm.ddlCustomers.items[0].text;
                    }
                });
        },
        cancelRecord: function () {
            clearAllMsgs();

            this.recordDTO.AliasId = 0;

            window.location.href = '/PCC/VPS/SDN/SDN.aspx?TI=3';
        },
        saveRecord: async function (e) {
            clearAllMsgs();
            //console.log(this.recordDTO);
            //return;
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            this.isLoading = true;
            const alphaNumRegex = /^[A-Za-z0-9_]+$/;

            if (this.recordDTO.AliasName == '' || this.recordDTO.Description == '' || this.recordDTO.Details.length <= 0) {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                this.isLoading = false;
                return false;
            }

            if (!alphaNumRegex.test(this.recordDTO.AliasName)) {
                displayErrorMsg(Error(this.getLabelText('AlphaNumericAliasNameRule')));
                this.isLoading = false;
                return false;
            }

            for (var i = 0; i < this.recordDTO.Details.length; i++) {
                var valIPOrNetworkOrFQDN = (this.recordDTO.Details[i].IPOrNetworkOrFQDN || '').toString().trim();
                //var valDescription = (this.recordDTO.Details[i].Description || '').toString().trim();

                if (valIPOrNetworkOrFQDN === '') {
                    displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                    this.isLoading = false;
                    return false;
                }

                //if ((this.recordDTO.AliasType == 'host' || this.recordDTO.AliasType == 'network') && valIPOrNetworkOrFQDN.indexOf('-') !== -1) {
                //    displayErrorMsg(Error(this.getLabelText('NetworkIPRangeNotAllowed')));
                //    this.isLoading = false;
                //    return false;
                //}

                //if (!alphaNumRegex.test(valIPOrNetworkOrFQDN)) {
                //    displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                //    this.isLoading = false;
                //    return false;
                //}
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'AliasDTO': this.recordDTO
            };
            postRequest.body = JSON.stringify(params);

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

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

            this.isLoading = false;
        },
    },
    created: async function () {

        var vm = this;

        await this.fillCustomers().then(vm.listRecords).catch(function (e) {

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

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