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 } 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 },
        sdnProviders: { type: Object, required: true },
        vpsServerGroups: { 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('GN0001183'),

            ddlProviders: this.sdnProviders,
            ddlServerGroup: this.vpsServerGroups,
            ddlHAGroupName: {},
            haGroupName: '',
        }
    },
    methods: {
        getLabelText,
        listRecords: async function() {
            if (this.recordDTO.SDNServerId > 0) {
                this.headerText = this.getLabelText('SPT002707');
                this.haGroupName = this.recordDTO.HAGroupName;

                if (this.recordDTO.HARole == 'slave')
                    this.fillHAGroupName();

                //await this.getRecordToEdit();
            }
            else {
                this.recordDTO = this.addEditDTO;
                this.recordDTO.VPSServerGroupId = this.ddlServerGroup.items[0].value;
                this.recordDTO.VPSServerGroupName = this.ddlServerGroup.items[0].text;
                this.recordDTO.SDNProviderId = this.ddlProviders.items[0].value;
                this.recordDTO.SDNProviderName = this.ddlProviders.items[0].text;
                this.recordDTO.HARole = 'master';
                this.haGroupName = '';

                this.headerText = this.getLabelText('GN0001183');
            }
        },
        fillHAGroupName: async function () {
            clearAllMsgs();

            var vm = this;
            vm.ddlHAGroupName = {};
            vm.recordDTO.HAGroupName = this.haGroupName;

            if (vm.recordDTO.HARole != 'slave')
                return;

            await fetch("/PCC/VPS/SDN/AddEditSDNServer.aspx/GetHANameOfMasterServersForSlave?vpsSGId=" + vm.recordDTO.VPSServerGroupId + "&pId=" + vm.recordDTO.SDNProviderId, fetchGet)
                .then(response => response.json()).then((data) => {

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

                    if (vm.ddlHAGroupName.items.length > 0) {
                        vm.recordDTO.HAGroupName = vm.ddlHAGroupName.items[0].value;
                    }
                }).catch(function (e) {

                    vm.isLoading = false;
                    displayErrorMsg(e);
                });
        },
        //getRecordToEdit: async function () {
        //    var vm = this;

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

        //            if (data.d != null) {

        //                vm.recordDTO = JSON.parse(data.d);
        //                vm.headerText = this.getLabelText('SPT002707');

        //                this.$emit('openAddEditSDNServer', vm.recordDTO);

        //            }
        //        }).catch(function (e) {
        //            displayErrorMsg(e);
        //        });
        //},
        providersChangeHandler: async function (obj) {
            this.recordDTO.SDNProviderId = obj.selectedValue;
            this.recordDTO.SDNProviderName = obj.selectedText;

            await this.fillHAGroupName();
        },
        serverGroupChangeHandler: async function (obj) {
            this.recordDTO.VPSServerGroupId = obj.selectedValue;
            this.recordDTO.VPSServerGroupName = obj.selectedText;

            await this.fillHAGroupName();
        },
        roleChangeHandler: async function () {
            await this.fillHAGroupName();
        },
        cancelRecord: function () {
            clearAllMsgs();
            
            this.recordDTO.SDNServerId = 0;

            window.location.href = '/PCC/VPS/SDN/SDN.aspx';
        },
        saveRecord: async function () {
            clearAllMsgs();
            this.isLoading = true;
            // alert(this.license);
            if (this.recordDTO.SDNServerName == '' || this.recordDTO.APIURL == '' || (this.recordDTO.SDNServerId == 0 && this.recordDTO.APIKey == '')) {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                this.isLoading = false;
                return false;
            }

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

            // Validate URL scheme: must start with http:// or https://
            if (!/^https?:\/\//i.test(this.recordDTO.APIURL)) {
                displayErrorMsg(Error(this.getLabelText('InvalidURL')));
                this.isLoading = false;
                return false;
            }

            var vm = this;

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

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

                    var sId = data.d;                    

                    if (vm.recordDTO.HARole == 'master' || !vm.recordDTO.IsHighAvailable) {
                        window.location.href = '/PCC/VPS/SDN/Interfaces.aspx?Id=' + sId + '&M=1';
                    }
                    else {
                        window.location.href = '/PCC/VPS/SDN/SDN.aspx?M=1';
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });

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

        var vm = this;

        await this.listRecords().catch(function (e) {
            
            vm.isLoading = false;
            displayErrorMsg(e);
        });

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