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 ModalPopUp from '/Components/Common/ModalPopUp.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,
        ModalPopUp,
        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: 'VPSServerID',
                sortDir: 'Asc',
                updateSorting: false
            },
            showClearButton: false,

            //***** START: Modal Popup *******
            showModalHealth: false,
            showModal: false,
            modalTitle: '',
            yesText: '',
            testServiceResult: '',
            parentContext: {},  //params to execute callback method related to current operation
            //***** END: Modal Popup *******
        }
    },
    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/GetServers", 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.records.map(obj => ({ ...obj, IsItemSelected: false }));
                });
            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);
                    console.log(vm.serverGroupObj);
                });

        },
        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);
            });
        },
        openVPNTab: 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;

            this.$emit('onOpenVPNTab', { serverId: sId, serverGroupId: this.serverGroupId, serverName: name, serverGroupName: this.records[0].ServerGroupName });
        },
        getCpuAndMemoryHistory: function (cbId, val) {
            //GetCpuAndMemoryHistory($(this), record.VPSServerGroupID + "|" + record.VPSServerID + "|" + record.IP); return false;
            clearAllMsgs();
            var vm = this;
            vm.showModalHealth = true;


            setTimeout(function () { GetCpuAndMemoryHistory($('#' + cbId), val); /*$('#serverHealth').modal('show');*/ }, 500);
        },
        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?'))
                this.removeRecord(sId);
        },
        removeRecord: function (sId) {

            var vm = this;

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

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

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

            let selectedRecords = this.records.filter(a => a.IsItemSelected);
           // Get comma - separated list of names
            const serverIds = selectedRecords.map(server => server.VPSServerID).join(',');
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

            if (disabledValue === 'true' || disabledValue === true)
                return false;

            let sId = 0;
            let enable = true;

            if (selectedRecords == null || selectedRecords == undefined || selectedRecords.length <= 0) {
                sId = e.target.dataset.id;
                enable =  e.target.dataset.active;
            }
            else {
                sId = serverIds;        
                enable = e.target.dataset.active;
            }
            //alert(sId);
            //alert(enable);
           
            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'ServerIds': sId,
                'Enable': enable //(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);
                });
        },
        mpModelEventHandler: function (obj) {
            this.testServiceResult = '';
            this.showModal = false;
            this.showModalHealth = false;
        },
        checkAll: function (checked) {
            this.records.map(obj => obj.IsItemSelected = checked);
        },
        showActionButton: function () {
            return this.records.find(obj => obj.IsItemSelected);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        testService: function (e) {
            clearAllMsgs();
            // 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;

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'ServerId': sId
            };

            postRequest.body = JSON.stringify(params);

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

                    vm.testServiceResult = data.d;
                    vm.modalTitle = this.getLabelText('L0096');
                    vm.showModal = true;
                }).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">

                        <ModalPopUp v-if="showModal" :id="'testService'" :parentContext="parentContext" :modalTitle="modalTitle" :yesButtonText="yesText" :noButtonText="getLabelText('GN000150')"
                            @onYes="mpModelEventHandler" @onNo="mpModelEventHandler">
                            <div class="row">
                                <div class="col-xs-12" v-html="testServiceResult">
                                </div>
                            </div>
                        </ModalPopUp>

                                <ModalPopUp v-if="showModalHealth" :id="'serverHealth'" :parentContext="parentContext" :modalTitle="modalTitle" :yesButtonText="yesText" :noButtonText="getLabelText('GN000150')"
                                @onYes="mpModelEventHandler" @onNo="mpModelEventHandler">
                                <div class="row">
                                    <div class="col-xs-12">
                                        <div class="card">
                                            <div class="header container-fluid">
                                                <h3 class="pull-left">
                                                    <label id="Lbl_UsagePopupHeader"></label>
                                                </h3>
                                            </div>
                                            <div class="body">
                                                <h4>{{ getLabelText('CPUUsage') }}</h4>
                                                <hr />
                                                <div class="row">
                                                    <div class="col-xs-12">
                                                        <div id="graph_CPU"></div>
                                                    </div>
                                                </div>
                                                <br />
                                                <h4>{{ getLabelText('MemoryUsage') }}</h4>
                                                <hr />
                                                <div class="row">
                                                    <div class="col-xs-12">
                                                        <div id="graph_Memory"></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </ModalPopUp>   

                        <OperationsPanel v-if="!readOnly">
                            <a v-bind:href="'/PCC/VPS/AddServer.aspx?SGId=' + this.serverGroupId" class="btn btn-primary waves-effect btnAction">{{ getLabelText('DGN1110098') }}</a>
                         <button id="btnEnable" class="btn btn-primary waves-effect btnAction" :data-active="true" v-if="!readOnly" @click.prevent="enableDisableServer" v-show="showActionButton()">{{getLabelText("strEnable")}}</button>
                         <button id="btnDisable" class="btn btn-primary waves-effect btnAction" :data-active="false" v-if="!readOnly" @click.prevent="enableDisableServer" v-show="showActionButton()">{{getLabelText("strDisable")}}</button>
                             </OperationsPanel>

                        
                        <div class="col-xs-12" v-if="serverGroupObj != null">
                            <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" v-if="records != null && records.length > 0 && records[0].ServerGroupProvider != ''">{{ getLabelText('DGN1110096') }}</td>
                                    <td width="30%" v-html="records[0].ServerGroupProvider" v-if="records != null && records.length > 0 && records[0].ServerGroupProvider != ''"></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-1 align-center">
                                            <input type="checkbox" id="CheckAll" :checked="checkAllChecked()" @change="checkAll($event.target.checked);" />
                                            <label for="CheckAll"></label>
                                        </th>
                                        <th class="col-xs-1 align-center">{{getLabelText('String385')}}</th>
                                        <th class="col-xs-4">{{ getLabelText('GN0000980') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('GN000174') }}</th>
                                        <th class="col-xs-4 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                            <td class="align-center">
                                            <input type="checkbox" v-bind:id="record.VPSServerID" v-model="record.IsItemSelected" />
                                            <label v-bind:for="record.VPSServerID"></label>
                                        </td>

                                        <td class="align-center">{{ (record.Active ? getLabelText('GN000195'): getLabelText('GN0000860')) }}</td>
                                        <td>{{ record.ReferenceID + ' (' + record.IP + ')' }}</td>
                                        <td>{{ record.IP  }}</td>
                                        <td>
                                            <a @click.prevent="openVPNTab" class="btn btn-primary waves-effect" :data-id="record.VPSServerID" :data-name="record.ReferenceID + ' (' + record.IP + ')'">{{ getLabelText('HVServer18') }}</a>
                                            <a @click.prevent="testService" :data-id="record.VPSServerID" class="btn btn-primary waves-effect">{{ getLabelText('String318') }}</a>
                                            <a v-if="!readOnly" @click.prevent="enableDisableServer" class="btn btn-primary waves-effect btnAction" :data-id="record.VPSServerID" :data-active="!record.Active" :data-name="record.ReferenceID + ' (' + record.IP + ')'">{{ (record.Active ? getLabelText('GN00001025'): getLabelText('GN00001024')) }}</a>
                                            <a class="btn btn-primary waves-effect" v-bind:href="'/PCC/VPS/EditServer.aspx?SGMemId=' + record.VPSServerID + '&SGid=' + record.VPSServerGroupID">{{ getLabelText('GN0000276') }}</a>
                                            <a  v-if="!readOnly" @click.prevent="confirmRemove" class="btn btn-primary waves-effect btnAction" :data-id="record.VPSServerID" :data-name="record.ReferenceID + ' (' + record.IP + ')'">{{ getLabelText('GN0000278') }}</a>
                                            <a :id="'Btn_HealthCheck' + record.VPSServerID" class="btn btn-primary" @click.prevent='getCpuAndMemoryHistory("Btn_HealthCheck" + record.VPSServerID,record.VPSServerGroupID + "|" + record.VPSServerID + "|" + record.IP);'>{{ getLabelText('strHealthCheck') }}</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>
`
}
