import VueSelect from '/Components/Common/VueSelect.js?v=3.6'
import InputSearch from '/Components/Common/InputSearch.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 { getLabelText } from '/Components/Common/utils.js?v=3.6'
import Loading from "/Components/Common/Loading.js?v=3.6"

export default {
    props: {
        serverGroupId: { type: String, required: true },
        readOnly: { type: Boolean, required: true },
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        Loading        
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            serverGroupObj: {},
            search: {
                serverGroupId: this.serverGroupId,

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'SubNetId',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    methods: {
        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.search.updateSorting = true;
            this.doSearch();
        },
        listRecords: async function () {

            var vm = this;
            vm.isLoading = true;
            let postRequest = { ...fetchPost };
            postRequest.body = JSON.stringify(vm.search);

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

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].TotalRecords;
                });
            vm.isLoading = false;
        },
        getServerGroup: async function () {

            var vm = this;

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

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

                    vm.serverGroupObj = JSON.parse(data.d);
                });

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.selectedStatus = '-1';

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                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 = {
                'SubNetId': sId
            };
            postRequest.body = JSON.stringify(params);

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

                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        enableDisableServerGroup: 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 currentStatus = e.target.dataset.active;
            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'ServerId': sId,
                'currentStatus': currentStatus //(isEnabled ? false : true)
            };
            //console.log(params, currentStatus);
            postRequest.body = JSON.stringify(params);

            fetch("/PCC/VPS/ServerGroups.aspx/EnableDisableServer", 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.getServerGroup().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    template: `

        <div class="col-xs-12">
            <div class="card">
                <div class="body">
                    <div class="row">

                        <OperationsPanel v-if="!readOnly">
                            <a v-bind:href="'/PCC/VPS/AddEditSubnetPool.aspx?SubNetId=0&b=0&SGId=' + serverGroupId" class="btn btn-primary waves-effect btnAction">{{ getLabelText('AddSubNetPool') }}</a>
                            <a v-bind:href="'/PCC/VPS/AddEditSubnetPool.aspx?SubNetId=0&b=1&SGId=' + serverGroupId" class="btn btn-primary waves-effect btnAction">{{ getLabelText('AddBulk') }}</a>
                        </OperationsPanel>

                        
                        <div class="col-xs-12" v-if="records.length > 0">
                            <table class="table table-bordered table-striped table-hover">
                                <tbody>
                                <tr>
                                    <td width="20%" class="row-label">{{ getLabelText('GN0000102') }}</td>
                                    <td width="30%" v-html="serverGroupObj.Name"></td>
                                    <td width="20%" class="row-label hide">{{ getLabelText('DGN1110096') }}</td>
                                    <td width="30%" class="hide" v-html="serverGroupObj.Name"></td>
                                </tr>
                                </tbody>
                            </table>
                        </div>                        

                       <div class="col-xs-12" v-if="isLoading">
                            <Loading/>
                        </div>
                        <div class="col-xs-12" v-else>
                            <table class="table table-bordered table-striped table-hover" v-if="records.length > 0">
                                <tbody>
                                    <tr>
                                        <th class="col-xs-3"><a href="#" @click.prevent="sortBy('SubNet')">{{getLabelText('strIPPoolName')}}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('Type')">{{ getLabelText('GN0000673') }}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('AllocationType')">{{ getLabelText('strAllocationType') }}</a></th>
                                        <th class="col-xs-2"><a href="#" @click.prevent="sortBy('Gateway')">{{ getLabelText('GN0000854') }}</a></th>
                                        <th class="col-xs-1"><a href="#" @click.prevent="sortBy('VLanId')">{{ getLabelText('HVServer32') }}</a></th>
                                        <th class="col-xs-2">{{ getLabelText('strUseforsharedVPShosting') }}</th>
                                        <th class="col-xs-2 align-center" v-if="!readOnly">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td><a v-bind:href="'/PCC/VPS/AddEditSubnetPool.aspx?SubNetId=' + record.SubNetId + '&SGId=' + serverGroupId" :data-id="record.SubNetId">{{ record.IPPoolName }}</a></td>
                                        <td>{{ (record.Type ? getLabelText('VPS990') : getLabelText('VPS991') ) }}</td>
                                        <td>{{ (record.AllocationType ? getLabelText('strDynamic') : getLabelText('strStatic') ) }}</td>
                                        <td>{{ record.Gateway }}</td>
                                        <td>{{ record.VLanId }}</td>
                                        <td>{{ record.IsSharedVPSHostingPool }}</td>
                                        <td v-if="!readOnly">
                                            <a @click.prevent="confirmRemove" class="btn btn-primary waves-effect btnAction" :data-id="record.SubNetId" :data-name="record.IPPoolName">{{ getLabelText('GN0000278') }}</a>                                            
                                        </td>                                        
                                    </tr>
                                    <Pager :totalRecords="totalRecords" :pageSize="this.search.pageSize" :currentPage="this.search.pageIndex" @pagerChange="pagerChangeHandler" />
                                </tbody>
                            </table>
                            <NoRecords v-else />
                        </div>
                    </div>
                </div>
            </div>
        </div>
`
}
