import InputText from "/Components/Common/InputText.js?v=3.9"
import NoRecords from '/Components/Common/NoRecords.js?v=3.9'
import { VueMultiSelectableSelected } from "/Components/Common/VueMultiSelectableSelected.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: {
        readOnly: { type: Boolean, required: true },
        sdnServerId: { type: String, required: true },
    },
    components: {
        InputText,
        NoRecords,
        Loading,
        VueMultiSelectableSelected,
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            records: [],
            customers: [],

            headerText: this.getLabelText('ManageInterfacesFor'), 
        }
    },
    methods: {
        getLabelText,
        listRecords: async function () {

            this.isLoading = true;
            var vm = this;

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

            fetch("/PCC/VPS/SDN/Interfaces.aspx/FetchSDNInterfaces", postRequest)
                .then(response => response.json()).then((data) => {
                    //console.log(data.d);
                    //[{"id":"wan","if":"hn0","enable":true,"descr":"WAN"},{"id":"lan","if":"hn1","enable":true,"descr":"LAN"},
                    //{ "id": "opt1", "if": "hn2", "enable": true, "descr": "OPT1" }, { "id": "opt9", "if": "hn3", "enable": true, "descr": "TENANTS" }, 
                    //{ "id": "opt10", "if": "hn4", "enable": true, "descr": "REPLICATION" }]

                    // parse records safely
                    vm.records = JSON.parse(data.d);

                    // Loop over vm.records and set/normalize properties for each object
                    vm.records.forEach(function (rec) {
                        // Normalize CustomerAssignmentIds to an array
                        if (rec.CustomerAssignmentIds == null) {
                            rec.CustomerAssignmentIds = [];
                            rec.CustomerAssignments = [];
                        }

                        if (rec.CustomerAssignmentIds.length > 0 && rec.InterfaceRole == 'TENANTS') {
                            rec.customers = vm.customers.map(c => ({ ...c }));

                            rec.customers.setSelectedListByListOfVals(rec.CustomerAssignmentIds);
                        }                       

                    });

                    this.headerText = this.getLabelText('ManageInterfacesFor') + ": " + this.records[0].SDNServerName;
                }).catch(function (e) {
                    displayErrorMsg(e);
                });

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

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

                    if (data.d != null) {
                        vm.customers = data.d;
                    }
                });
        },
        selectionCustomerHandler: function (selectableItems, selectedItems, id) {
            let index = id.toString().split("_")[1];
            this.records[index].CustomerAssignmentIds = selectedItems.map(x => x.value);
            this.records[index].CustomerAssignments = selectedItems.map(x => x.text);

            //console.log("Selectable: " + JSON.stringify(selectableItems));
            //console.log("Selected: " + JSON.stringify(selectedItems));

            //console.log(index + ' on ' + this.records[index].CustomerAssignments);
        },
        handleTenantCustomerAssignment: function (record, newUsedFor) {
            //console.log('in handler', record.InterfaceRole);

            record.InterfaceRole = newUsedFor;

            if (record.InterfaceRole == 'TENANTS') {
                record.customers = this.customers.map(c => ({ ...c }));

                if (record.CustomerAssignmentIds.length > 0)
                    record.customers.setSelectedListByListOfVals(record.CustomerAssignmentIds);
            }
                   
        },
        saveRecord: async function () {
            clearAllMsgs();
            this.isLoading = true;

            //***** Delete unnecessary properties before sending to server, otherwise model binding on server won't work and properties will be null.
            this.records.forEach(d => { if (d.customers) { delete d.customers; } });            

            // validate TENANTS assignments: if any TENANTS interface has no customer assignment, stop
            let selectedRecords = this.records.filter(a =>
                a.InterfaceRole === 'TENANTS' &&
                (a.CustomerAssignmentIds === '' ||
                 a.CustomerAssignmentIds == null ||
                 (Array.isArray(a.CustomerAssignmentIds) && a.CustomerAssignmentIds.length === 0))
            );

            if (selectedRecords != null && selectedRecords.length > 0) {
                displayErrorMsg(Error(this.getLabelText('strCustomerSelectWithTENANTS')));
                this.isLoading = false;
                return false;
            }

            var vm = this;

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

            await fetch("/PCC/VPS/SDN/Interfaces.aspx/SaveSDNInterfaces", postRequest)
                .then(response => response.json()).then((data) => {
                    //displaySuccessMsg(data.d);

                    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.fillCustomers().then(vm.listRecords).catch(function (e) {
            vm.records = [];
            vm.isLoading = false;
            displayErrorMsg(e);
        });
    },
    updated: function () {
        //updateSelectInterface();
        //AdminBSBThemeChanges();
    },
    template: '#vpssdninterfaces-template',
}
