import VueSelect from '/Components/Common/VueSelect.js?v=3.9'
import InputSearch from '/Components/Common/InputSearch.js?v=3.9'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.9'
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.9'
import Pager from '/Components/Common/Pager.js?v=3.9'
import NoRecords from '/Components/Common/NoRecords.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 },
    },
    components: {
        SearchPanel,
        OperationsPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            search: {
                selectedStatus: '-1',

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'Name',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,
        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        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();
        },
        statusChangeHandler: function (obj) {
            this.search.selectedStatus = obj.selectedValue;
        },
        listRecords: async function () {

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

            await fetch("/PCC/VPS/ServerGroups.aspx/GetServerGroups", 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;
        },
        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);
            });
        },
        openServersTab: 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;
            let provider = e.target.dataset.provider;

            this.$emit('onOpenServersTab', { serverGroupId: sId, serverGroupName: name, serverGroupProvider: provider });
        },
        openSubNetPoolTab: 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;
            let provider = e.target.dataset.provider;

            this.$emit('onOpenSubNetPoolTab', { serverGroupId: sId, serverGroupName: name, serverGroupProvider: provider });
        },
        openDNSPoolTab: 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;
            let provider = e.target.dataset.provider;

            this.$emit('onOpenDNSPoolTab', { serverGroupId: sId, serverGroupName: name, serverGroupProvider: provider });
        },
        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('Are you sure you want to remove ' + Name + ' Server Group?'))
                this.removeRecord(sId);
        },
        removeRecord: function (sId) {

            var vm = this;

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

            fetch("/PCC/VPS/ServerGroups.aspx/RemoveServerGroup", 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 = {
                'ServerGroupId': sId,
                'currentStatus': currentStatus //(isEnabled ? false : true)
            };
            //console.log(params, currentStatus);
            postRequest.body = JSON.stringify(params);

            fetch("/PCC/VPS/ServerGroups.aspx/EnableDisableServerGroup", 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.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/AddServerGroup.aspx'" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000970') }}</a>
                        </OperationsPanel>

                        <SearchPanel id='vpsservergroups-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>

                            <div :class="searchContainerDivClass">
                                <div class="form-group form-float">
                                    <select v-model="search.selectedStatus" class="vue-select">
                                        <option value="-1">{{getLabelText("GN0000934")}}</option>
                                        <option value="1">{{getLabelText("GN00001309")}}</option>
                                        <option value="0">{{getLabelText("GN00001310")}}</option>
                                    </select>
                                </div>
                            </div>

                        </SearchPanel>

                        <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-1 align-center">{{getLabelText('String385')}}</th>
                                        <th class="col-xs-6"><a href="#" @click.prevent="sortBy('Name')">{{ getLabelText('GN0000971') }}</a></th>
                                        <th class="col-xs-3">{{ getLabelText('DGN1110096') }}</th>
                                        <th class="col-xs-1 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">

                                        <td class="align-center">{{ (record.Active ? getLabelText('GN000195'): getLabelText('GN0000860')) }}</td>
                                        <td><a @click.prevent="openServersTab" :data-id="record.VPSServerGroupID" :data-provider="getLabelText(record.Trans_Id)" :data-name="record.Name + (record.ClusterName != '' ? ' [' + record.ClusterName + ']' : '')">{{ record.Name + (record.ClusterName != '' ? ' [' + record.ClusterName + ']' : '') }}</a></td>
                                        <td>{{ getLabelText(record.Trans_Id) /*record.ProviderName*/ }}</td>
                                        <td class="align-center">
                                            <ul class="option-menu">
                                                <li class="dropdown">
                                                    <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                                        <i class="material-icons">menu</i>
                                                    </a>
                                                    <ul class="dropdown-menu pull-right">
                                                        <li v-if="!readOnly">
                                                            <a v-bind:href="'/PCC/VPS/AddServer.aspx?SGId=' + record.VPSServerGroupID" class="btnAction">{{ getLabelText('DGN1110093') }}</a>
                                                        </li>
                                                        <li v-if="!readOnly">
                                                            <a class="btnAction" @click.prevent="enableDisableServerGroup" :data-id="record.VPSServerGroupID" :data-active="record.Active">{{ (record.Active ? getLabelText('GN00001025'): getLabelText('GN00001024')) }}</a>
                                                        </li>
                                                        <li>
                                                            <a v-bind:href="'/PCC/VPS/EditServerGroup.aspx?SGId=' + record.VPSServerGroupID" class="">{{ getLabelText('GN0000276') }}</a>
                                                        </li>
                                                        <li>
                                                            <a @click.prevent="openSubNetPoolTab" :data-id="record.VPSServerGroupID" :data-provider="getLabelText(record.Trans_Id)" :data-name="record.Name + (record.ClusterName != '' ? ' [' + record.ClusterName + ']' : '')" class="">{{ getLabelText('VPS992') }}</a>
                                                        </li>
                                                        <li>
                                                            <a @click.prevent="openDNSPoolTab" :data-id="record.VPSServerGroupID" :data-provider="getLabelText(record.Trans_Id)" :data-name="record.Name + (record.ClusterName != '' ? ' [' + record.ClusterName + ']' : '')" class="">{{ getLabelText('VPS993') }}</a>
                                                        </li>
                                                        <li v-if="!readOnly">
                                                            <a class="btnAction" @click.prevent="confirmRemove" :data-id="record.VPSServerGroupID" :data-name="record.Name">{{ getLabelText('GN0000278') }} </a>
                                                        </li>
                                                    </ul>
                                                </li>
                                            </ul>
                                        </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>
`
}
