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

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        sdnServersFilter: { type: Object, required: true },
        vpsServersFilter: { type: Object, required: true },
        customerId: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
    },
    components: {
        SearchPanel,
        OperationsPanel,
        VueSelect,
        InputSearch,
        InputText,
        NoRecords,
        ModalPopUp,
        Pager,
        Loading,
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            records: [],
            owners: {},
            avaIPs: {},
            sdnServers: this.sdnServersFilter,
            vpsServers: this.vpsServersFilter,
            showClearButton: false,
            totalRecords: 0,
            search: {
                selectedOwner: '-1',
                customerId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                customerCompanyName: '',
                vmName: '',
                subscriptionId: '',
                selectedSDNServerId: '-1',
                selectedVPSServerId: '-1',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'CustomerID',
                sortDir: 'DESC'

            },
            showClearButton: false,

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: '',
            yesText: '',
            noText: '',
            parentContext: {},  //params to execute callback method related to current operation

            showIPModal: false,
            iPModalTitle: '',
            selectedIP: '',
            description: '',
            macaddress: '',



            //***
        }
    },
    methods: {
        ownerChangeHandler: function (obj) {
            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);
        },
        sdnServersChangeHandler: function (obj) {
            this.search.selectedSDNServerId = obj.selectedValue;
        },
        vpsServersChangeHandler: function (obj) {
            this.search.selectedVPSServerId = obj.selectedValue;
        },
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        ipChangeHandler: function (obj) {
            this.selectedIP = obj.selectedValue;
        },
        getLabelText,
        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();
        },
        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);
                });
        },
        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/GetSDNVMIPBindings", 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;
        },
        confirmRemove: function (e) {

            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');
            // alert(disabledValue);
            if (disabledValue === 'true' || disabledValue === true)
                return false;

            // alert('in confirmRemove');
            let CompanyId = e.target.dataset.companyid;
            let CustomerId = e.target.dataset.customerid;
            let ID = e.target.dataset.id;
            let VPSId = e.target.dataset.vpsid;
            let IP = e.target.dataset.ip;
            let MAC = e.target.dataset.mac;
            let ServerId = e.target.dataset.sdnserverid;
            let DHCPIPId = e.target.dataset.dhcpipid;

            //alert(e.target.dataset.dhcp);
            //console.log(e.target.dataset);

            if (confirm(this.getLabelText('StaticIPRemoveConfirmMsg').replace('%operand%', IP))) {
                this.removeRecord(CompanyId, CustomerId, ID, VPSId, IP, MAC, ServerId, DHCPIPId);
            }
        },
        removeRecord: function (CompanyId, CustomerId, ID, VPSId, IP, MAC, ServerId, DHCPId) {
            this.isLoading = true;
            var vm = this;
            //alert(vlanId);
            let postRequest = { ...fetchPost };
            let params = {
                'CompanyId': CompanyId,
                'CustomerId': CustomerId,
                'Id': ID,
                'VPSId': VPSId,
                'Ip': IP,
                'Mac': MAC,
                'SDNServerId': ServerId,
                'DHCPIPId': DHCPId
            };
            postRequest.body = JSON.stringify(params);
            // alert(params);
            fetch("/PCC/VPS/SDN/SDN.aspx/RemoveStaticIP", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
            
            this.isLoading = false;

        },
        listAvaibleIPs: function (ID) {
            var vm = this;
            let postRequest = { ...fetchPost };
            let params = {
                'RecordId': ID

            };
            // alert(ID);
            postRequest.body = JSON.stringify(params);
            fetch("/PCC/VPS/SDN/SDN.aspx/GetAvailableSDNIPAddresses", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.avaIPs = JSON.parse(data.d);
                    vm.selectedIP = vm.avaIPs.initialValue;
                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        assignIP: function (obj) {
            var vm = this;
            this.isLoading = true;
            //let Id = e.target.dataset.id;
            //alert(Id);
            let postRequest = { ...fetchPost };
            let params = {
                //"ADUserId": obj.parentContext.AdUserId,
                //"CompanyId": obj.parentContext.CompanyId,
                //"Password": vm.password
                'CompanyId': obj.parentContext.CompanyId,
                'CustomerId': obj.parentContext.CustomerId,
                'Id': obj.parentContext.RecordId,
                'IP': vm.selectedIP,
                'Mac': obj.parentContext.MACAddress,
                'SDNServerId': obj.parentContext.SDNServerId,
                'DHCPIPId': obj.parentContext.DHCPId,
                'Desc': vm.description

            }
            console.log(params);
            postRequest.body = JSON.stringify(params);

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

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

            vm.showIPModal = false;           
            this.isLoading = false;

        },
        showAssignIPChangePopUP: async function (companyid, customerid, recordId, serverId, macAdd, dId) {

            var vm = this;
            vm.listAvaibleIPs(recordId);
            vm.showIPModal = true;
            vm.yesText = getLabelText('DEV1181');
            vm.noText = getLabelText('GN0000572');
            vm.iPModalTitle = getLabelText('AssignStaticIP');
            vm.selectedIP = "";
            vm.description = "";
            vm.macaddress = macAdd;
            vm.recordId = recordId;
            vm.parentContext = { CompanyId: companyid, CustomerId: customerid, RecordId: recordId, SDNServerId: serverId, MACAddress: macAdd, DHCPId: dId };
        },
        mpModelEventHandler: function (obj) {
            this.recordDetails = [];
            this.showIPModal = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            //this.search.selectedOwner = '-1';
            this.search.selectedSDNServerId = '-1';
            this.search.selectedVPSServerId = '';
            this.search.vmName = '';
            this.search.subscriptionId = '';
            this.search.customerId = '';
            this.search.customerName = '';
            this.search.customerCompanyName = '';
            this.search.pageIndex = 1;
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },



    },
    created: async function () {

        var vm = this;

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

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