import VueSelect from '/Components/Common/VueSelect.js?v=3.6'
import InputSearch from '/Components/Common/InputSearch.js?v=3.6'
import InputText from "/Components/Common/InputText.js?v=3.6"
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.6'
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.6'
import Pager from '/Components/Common/Pager.js?v=3.6'
import NoRecords from '/Components/Common/NoRecords.js?v=3.6'
import Loading from "/Components/Common/Loading.js?v=3.6"
import { getLabelText } from '/Components/Common/utils.js?v=3.6'

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        sdnServersFilter: { type: Object, required: true },
        sdnInterfacesForInput: { type: Object, required: true },
        sdnInterfacesFilter: { type: Object, required: true },
        customerId: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
    },
    components: {
        SearchPanel,
        VueSelect,
        OperationsPanel,
        InputSearch,
        InputText,
        NoRecords,
        Pager,
        Loading,
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            records: [],
            owners: {},
            sdnServers: this.sdnServersFilter,
            sdnInterfaces: this.sdnInterfacesFilter,
            sdnInterfacesInput: this.sdnInterfacesForInput,
            sdnInterfacesInputValue: this.sdnInterfacesForInput.items[0].value,
            sdnInterfacesInputText: this.sdnInterfacesForInput.items[0].text,
            showClearButton: false,

            totalRecords: 0,

            protocols: {
                show: true,
                initialValue: '-1',
                items: [
                    { text: this.getLabelText('SelectProtocol'), value: '-1' },
                    { text: 'Any', value: 'Any' },
                    { text: 'TCP', value: 'TCP' },
                    { text: 'UDP', value: 'UDP' },
                    { text: 'TCP/UDP', value: 'TCPUDP' }
                ] },
            actions: {
                show: true,
                initialValue: '-1',
                items: [
                    { text: this.getLabelText('GN0001198'), value: '-1' },
                    { text: 'Pass', value: 'Pass' },
                    { text: 'Block', value: 'Block' },
                    { text: 'Reject', value: 'Reject' } 
                ] },
            enabledOptions: {
                show: true,
                initialValue: '-1',
                items: [
                    { text: this.getLabelText('SelectStatus'), value: '-1' },
                    { text: this.getLabelText('strEnabled'), value: '1' },
                    { text: this.getLabelText('strDisabled'), value: '0' }
                ]
            },
             
            search: {
                selectedOwner: "-1",
                customerId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                customerCompanyName: '',
                selectedSDNServerId:"-1",
                interfaceName: '-1',
                source: '',
                destination: '',
                protocol: -1,
                action: -1,
                enabled: "-1",
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'VLANInterfaceId,DisplayOrder,Description',
                sortDir: 'Asc'
            }
        }
    },
    methods: {
        getLabelText,

        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit === true)
                this.doSearch();
        },
        listOwners: async function () {
            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/GetOwners", fetchGet)
                .then(response => response.json()).then((data) => {
                    vm.owners = JSON.parse(data.d);
                    this.search.selectedOwner = vm.owners.initialValue;
                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        ownerChangeHandler: function (obj) {
            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);
        },
        sdnServersChangeHandler: function (obj) {
            this.search.selectedSDNServerId = obj.selectedValue;
        },
        interfacesChangeHandler: function (obj) {
            this.search.interfaceName = obj.selectedValue;
        },
        sdnInterfacesInputValueChangeHandler: function (obj) {
            this.sdnInterfacesInputValue = obj.selectedValue;
            this.sdnInterfacesInputText = obj.selectedText;
        },
        protocolChangeHandler: function (obj) {
            this.search.protocol = obj.selectedValue;
        },
        actionChangeHandler: function (obj) {
            this.search.action = obj.selectedValue;
        },
        enabledChangeHandler: function (obj) {
            this.search.enabled = obj.selectedValue;
        },
        sortBy: function (exp) {
            if (this.search.sortExpression !== exp) {
                this.search.sortExpression = exp;
                this.search.sortDir = "Asc";
            } else {
                this.search.sortDir = this.search.sortDir === "Asc" ? "Desc" : "Asc";
            }
            this.doSearch();
        },
        listRecords: async function () {
            var vm = this;
            vm.isLoading = true;
            let postRequest = { ...fetchPost };

            postRequest.body = JSON.stringify(vm.search);

            await fetch("/PCC/VPS/SDN/SDN.aspx/GetSDNFirewallRules", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].Counter;
                });

            vm.isLoading = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: function () {
            this.search.customerId = (this.customerId != '0' ? this.customerId : '');
            this.search.customerName = '';
            this.search.customerCompanyName = '';
            this.search.selectedSDNServerId = -1;
            this.search.interfaceName = '-1';
            this.search.source = '';
            this.search.destination = '';
            this.search.protocol = -1;
            this.search.action = -1;
            this.search.enabled = "-1";
            this.pageIndex = 1;
            this.pageSize = gridPageSize;
            this.sortExpression = 'API_If';
            this.sortDir = 'Asc';
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            this.pageIndex = 1;
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        confirmRemove: function (e) {
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            let sId = e.target.dataset.id;
            let name = e.target.dataset.name;

            if (confirm(this.getLabelText('CBE001').replace('%operand%', name)))
                this.removeRecord(sId);
        },
        removeRecord: function (sId) {

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'RuleId': sId,
            };
            postRequest.body = JSON.stringify(params);

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

                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        updatePriorityOrder: async function () {
            clearAllMsgs();
            this.isLoading = true;
            var vm = this;

            for (var i = 0; i < this.records.length; i++) {
                var valDisplayOrder = (this.records[i].DisplayOrder || '').toString().trim();

                if (valDisplayOrder === '') {
                    displayErrorMsg(Error('Priority order is required.'));
                    this.isLoading = false;
                    return false;
                }

                // Ensure DisplayOrder is a numeric value. If empty, non-numeric, or <= 0 -> default to 1.
                var parsed = parseInt(valDisplayOrder, 10);
                if (valDisplayOrder === '' || isNaN(parsed) || parsed <= 0) {
                    this.records[i].DisplayOrder = 1;
                } else {
                    this.records[i].DisplayOrder = parsed;
                }
            }


            let postRequest = { ...fetchPost };
            let payload = {
                data: { Rules: this.records }
            };
            postRequest.body = JSON.stringify(payload);

            await fetch("/PCC/VPS/SDN/SDN.aspx/SaveRulesPriorityOrder", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });

            this.isLoading = false;
        },
        confirmReset: async function (e) {
            clearAllMsgs();
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            //let sId = e.target.dataset.id;
            //let name = e.target.dataset.name;

            if (confirm(this.getLabelText('ResetFirewallRulesToDefaultConfirm').replace('%operand%', this.sdnInterfacesInputText)))
                await this.resetRecords();
        },
        resetRecords: async function () {

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'VLANValue': this.sdnInterfacesInputValue,
                'VLANText': this.sdnInterfacesInputText
            };
            postRequest.body = JSON.stringify(params);

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

                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
    },

    created: async function () {
        var vm = this;
        await this.listOwners().then(vm.listRecords).catch(function (e) {
            vm.records = [];
            vm.isLoading = false;
            displayErrorMsg(e);
        });
    },

    template: '#vpssdnfirewall-template',
}
