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 },
        isLoggedInAsCustomer: { 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('AddNATSettings'),

            ddlCustomers: {},
            ddlNATIP: {},
            selectedNATValue: '0|0',
            selectedNATText: '',
            ddlDestinationIP: {},
            ddlSource: {},
            ddlProtocol: {
                show: true,
                initialValue: 'any',
                items: [
                    { text: 'Any', value: 'any' },
                    { text: 'TCP', value: 'tcp' },
                    { text: 'UDP', value: 'udp' },
                    { text: 'TCP/UDP', value: 'tcp/udp' }
                ]
            },
        }
    },
    methods: {
        getLabelText,
        listRecords: async function () {
            if (this.recordDTO.NATId > 0) {
                //this.headerText = this.getLabelText('EditNATSetting');

                //await this.fillNATIPs();
                //this.selectedNATValue = this.recordDTO.RedirectTargetIPId + '|' + this.recordDTO.SDNServerId;
                //this.selectedNATText = this.recordDTO.RedirectTargetIP;
                ////await this.getRecordToEdit();
            }
            else {
                this.recordDTO = this.addEditDTO;
                this.recordDTO.CustomerId = this.ddlCustomers.items[0].value;
                this.recordDTO.CustomerName = this.ddlCustomers.items[0].text;

                this.headerText = this.getLabelText('AddNATSetting');

                //await this.fillNATIPs();
            }
            
            //await this.fillDestinationIPs();
            //await this.fillSource();
        },
        customerChangeHandler: async function (obj) {
            clearAllMsgs();
            var vm = this;

            this.recordDTO.CustomerId = obj.selectedValue;
            this.recordDTO.CustomerName = obj.selectedText;

            await this.fillNATIPs().then(vm.fillSource).then(vm.fillDestinationIPs).catch(function (e) {

                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        fillCustomers: async function () {
            var vm = this;
            vm.ddlCustomers = {};
            vm.ddlNATIP = {};
            vm.ddlSource = {};
            vm.ddlDestinationIP = {};

            await fetch("/PCC/VPS/SDN/ManageNAT.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.NATId <= 0) {
                        vm.recordDTO.CustomerId = vm.ddlCustomers.items[0].value;
                        vm.recordDTO.CustomerName = vm.ddlCustomers.items[0].text;
                    }
                });
        },
        natIPChangeHandler: async function (obj) {
            clearAllMsgs();
            var vm = this;

            this.selectedNATValue = obj.selectedValue;
            this.selectedNATText = obj.selectedText;

            this.recordDTO.RedirectTargetIPId = obj.selectedValue.toString().split('|')[0];
            this.recordDTO.SDNServerId = obj.selectedValue.toString().split('|')[1];
            this.recordDTO.RedirectTargetIP = obj.selectedText;

            await this.fillSource().then(vm.fillDestinationIPs).catch(function (e) {

                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        fillNATIPs: async function () {
            var vm = this;
            vm.ddlNATIP = {};
            vm.ddlSource = {};
            vm.ddlDestinationIP = {};

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

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

                    //**** Avoid to set default value when in edit mode ****//
                    if (vm.ddlNATIP.items.length > 0 && vm.recordDTO.NATId <= 0) {
                        vm.recordDTO.RedirectTargetIPId = vm.ddlNATIP.items[0].value.toString().split('|')[0];
                        vm.recordDTO.SDNServerId = vm.ddlNATIP.items[0].value.toString().split('|')[1];
                        vm.recordDTO.RedirectTargetIP = vm.ddlNATIP.items[0].text;

                        vm.selectedNATValue = vm.ddlNATIP.items[0].value;
                        vm.selectedNATText = vm.ddlNATIP.items[0].text;


                    }
                });
        },
        destinationIPChangeHandler: function (obj) {
            clearAllMsgs();

            this.recordDTO.DestinationIPAddressId = obj.selectedValue;
            this.recordDTO.DestinationIP = obj.selectedText;
        },
        fillDestinationIPs: async function () {
            var vm = this;
            vm.ddlDestinationIP = {};

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

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

                    //**** Avoid to set default value when in edit mode ****//
                    if (vm.ddlDestinationIP.items.length > 0 && vm.recordDTO.NATId <= 0) {
                        vm.recordDTO.DestinationIPAddressId = vm.ddlDestinationIP.items[0].value;
                        vm.recordDTO.DestinationIP = vm.ddlDestinationIP.items[0].text;
                    }
                });
                //.catch(function (e) {
                //    vm.isLoading = false;
                //    displayErrorMsg(e);
                //});
        },
        protocolChangeHandler: function (obj) {
            this.recordDTO.Protocol = obj.selectedValue;
        },
        sourceChangeHandler: function (obj) {
            clearAllMsgs();

            this.recordDTO.Source = obj.selectedValue;
        },
        fillSource: async function () {
            var vm = this;
            vm.ddlSource = {};
            vm.ddlDestinationIP = {};

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

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

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

            this.recordDTO.NATId = 0;

            window.location.href = '/PCC/VPS/SDN/SDN.aspx?TI=6';
        },
        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;

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

            var vm = this;

            vm.recordDTO.RedirectTargetIPId = vm.selectedNATValue.toString().split('|')[0];
            vm.recordDTO.SDNServerId = vm.selectedNATValue.toString().split('|')[1];
            vm.recordDTO.RedirectTargetIP = vm.selectedNATText;
            //alert(vm.selectedNATValue.toString().split('|')[2]);
            let postRequest = { ...fetchPost };
            let params = {
                'NATDTO': this.recordDTO,
                'VPSId': vm.selectedNATValue.toString().split('|')[2]
            };
            postRequest.body = JSON.stringify(params);

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

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

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

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

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

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