//TODO: 1-Edit Button functionality remaing. 2-Add databases remaining

import { getLabelText } from '/components/common/utils.js?v=3.4'
import VueSelect from "/Components/Common/VueSelect.js?v=3.4"
import InputSearch from "/Components/Common/InputSearch.js?v=3.4"
import Pager from "/Components/Common/Pager.js?v=3.4"
import SearchPanel from "/Components/Common/SearchPanelWrapper.js?v=3.4"
import NoRecords from "/Components/Common/NoRecords.js?v=3.4";
import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"

export default {

    props: {
        //tabIndex: { type: String, required: true },
        readOnly: { type: Boolean, required: true },
        showDeleteOption: { type: Boolean, required: true }
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        Pager,
        SearchPanel,
        NoRecords,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            serverGroups: {},
            records: [],
            search: {
                selectedServerGroup: '',
                dbName: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'DatabaseName',
                sortDir: 'Desc',
                updateSorting: false
            },
            globalSettings: {},
            showClearButton: false,

        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

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

            this.search.selectedServerGroup = obj.selectedValue;


        },
        fillExchServerGroups: async function (advanceManagement) {

            var vm = this;

            let postRequest = { ...fetchPost };
            var params = {
                AdvanceManagement: advanceManagement
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/webservices/machpanelservice.asmx/GetExchServerGroups", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.serverGroups = JSON.parse(data.d);                  
                    this.search.selectedServerGroup = vm.serverGroups.items[0].value;                  
                });

        },
        checkAll: function (checked) {
            this.records.map(obj => obj.IsItemSelected = checked);
        },
        checkAllChecked: function () {
            return !this.records.find(obj => !obj.IsItemSelected);
        },
        listRecords: async function () {

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

            await fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/FillAdvDataBases", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0) {
                        vm.totalRecords = vm.records[vm.records.length - 1].TotalRecords;
                        vm.records.pop();
                    }
                });
            vm.isLoading = false;
        },
        getLabelText,
        confirmRemove: function (dbName, mailBoxServer) {

            if (confirm(this.getLabelText('GN000200')))
                this.removeAdvDB(dbName, mailBoxServer);
        },
        removeAdvDB: function (dbName, mailBoxServer) {

            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {

                'ServerGroupId': vm.search.selectedServerGroup,
                'DBname': dbName,
                'MailBoxServer': mailBoxServer
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/RemovAdveDB", postRequest)
                .then(response => response.json()).then((data) => {                   
                    this.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011')); //


                }).catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        mountDB: function (dbName) {

            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {

                'ServerGroupId': vm.search.selectedServerGroup,
                'DBname': dbName
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/MountDB", postRequest)
                .then(response => response.json()).then((data) => {                  
                    this.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011')); //


                }).catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        dismountDB: function (dbName) {

            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {

                'ServerGroupId': vm.search.selectedServerGroup,
                'DBname': dbName
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/DisMountDB", postRequest)
                .then(response => response.json()).then((data) => {                  
                    this.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011')); //


                }).catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        diskSizeCalc: function (Size) {

            if(Size >= 1024)
            {
                Size = (Size / 1024).toFixed(2);
                if(Size >= 1024)
                {
                    Size = (Size / 1024).toFixed(2);
                    if (Size >= 1024)
                    {
                        //Size = (Size / 1024).toFixed(2);
                        //if (Size >= 1024) {
                        //}
                        //else {
                            Size = Size + " TB";
                       // }
                    }
                    else
                    {
                        Size = Size + " GB";
                    }
                }
                else
                {
                    Size = Size + " MB";
                }
            }
           else
            {
                Size = Size + " KB";
            }  

            return Size;
        },
        doClearSearch: async function () {

            // this.search.selectedorg = this.orgs.initialValue;


            this.search.DBName = '';
            this.search.pageIndex = 1;
            //this.search.pageSize = gridPageSize;
            //this.search.sortExpression = '';
            //this.search.sortDir = 'Asc';

            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.settings = [];
                if (vm.settings.length > 0)
                    vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        }        
    },
    
created: async function () {    
    var vm = this;

    await this.fillExchServerGroups(false).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>
                        <a @click="" class="btn btn-primary waves-effect btnAction">{{ getLabelText('SPT002083') }}</a>
                    </OperationsPanel>

                    <SearchPanel id='record-list' :showClearButton="showClearButton" @onSearch='doSearch' @onClear='doClearSearch'>
                        
                        <div :class="searchContainerDivClass" v-if="serverGroups.show">
                            <div class="form-group form-float">
                                <VueSelect :options="serverGroups.items" :selectedValue="this.search.selectedServerGroup" @selectchange="serverGroupChangeHandler" />
                            </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-2">{{getLabelText("SPT002073")}}</th>
                                    <th class="col-xs-2">{{getLabelText("DGN1110254")}}</th>
                                    <th class="col-xs-2">{{getLabelText("DatabaseAvailabilityGroup")}}</th>
                                    <th class="col-xs-1">{{getLabelText("ActiveCopyStatus")}}</th>
                                    <th class="col-xs-4">{{getLabelText("strDetails")}}</th>
                                    <th class="col-xs-1">{{getLabelText("GN0000360")}}</th>                                     
                                </tr>
                                <tr v-for="record in records">
                                    <td>{{record.DatabaseName}}</td>
                                    <td>{{record.MailboxServer}}</td>
                                    <td>{{record.MasterServerOrAvailabilityGroup}}</td>
                                    <td v-if="record.ActiveCopy == 1">{{getLabelText("Active")}}</td>
                                    <td v-else>{{getLabelText("Passive")}}</td>

                                    <td>
                                        <table class="table small">
                                            <tbody>
                                                <tr>
                                                    <td class="col-xs-5 row-label">
                                                        {{getLabelText("CopyQueueLength")}}:                                                            
                                                    </td>
                                                    <td class="col-xs-8">
                                                      {{record.CopyQueueLength}}
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="col-xs-5 row-label">
                                                          {{getLabelText("ReplayQueueLength")}}:                                                          
                                                    </td>
                                                    <td class="col-xs-8">
                                                        {{record.ReplayQueueLength}}
                                                    </td>
                                                </tr>
                                                <tr >
                                                    <td class="col-xs-5 row-label">
                                                        {{getLabelText("LastInspectedLogTime")}}:
                                                    </td>
                                                    <td class="col-xs-8">
                                                        {{record.LastInspectedLogTime}} 
                                                    </td>
                                                </tr>
                                                <tr >
                                                    <td class="col-xs-5 row-label">
                                                        {{getLabelText("strDatabaseSizeonDisk")}}:
                                                    </td>
                                                    <td class="col-xs-8">
                                                        {{diskSizeCalc(record.DatabaseSize)}} 
                                                    </td>
                                                </tr>   
                                                <tr >
                                                    <td class="col-xs-5 row-label">
                                                        {{getLabelText("ContentIndexState")}}:
                                                    </td>
                                                    <td class="col-xs-8">
                                                        {{record.ContentIndexState}} 
                                                    </td>
                                                </tr>
                                                <tr >
                                                    <td class="col-xs-5 row-label">
                                                        {{getLabelText("CircularLoggingEnabled")}}:
                                                    </td>
                                                    <td class="col-xs-8" v-if="record.CircularLoggingEnabled == 1">
                                                        {{record.GN0000553}} 
                                                    </td>
                                                    <td class="col-xs-8" v-else>
                                                        {{getLabelText("GN0000552")}}
                                                    </td>
                                                </tr>
                                               <tr >
                                                    <td class="col-xs-5 row-label">
                                                        {{getLabelText("Mounted")}}:
                                                    </td>
                                                    <td class="col-xs-8" v-if="record.Mounted == 1">
                                                        {{getLabelText("GN0000553")}}
                                                    </td>
                                                    <td class="col-xs-8" v-else>
                                                        {{getLabelText("GN0000552")}}
                                                    </td>
                                                </tr>

                                            </tbody>
                                        </table>
                                    </td>
                                     <td class="align-center" v-if="!readOnly">
                                     
                                            <ul class="option-menu Div_OpsRow">
                                                <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" id="UL_OptionMenu">
                                                        
                                                        <li v-if="record.ActiveCopy == 1 && record.CircularLoggingEnabled !=1">
                                                            <a @click="CopyDB" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('GN0001159') }}</a>
                                                         </li>
                                                        <li v-if="record.Mounted == 1">
                                                            <a @click="dismountDB(record.DatabaseName,record.MailboxServer)" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('ExDB05') }}</a>
                                                        </li>
                                                        <li v-else>
                                                            <a @click="mountDB(record.DatabaseName,record.MailboxServer)" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('ExDB04') }}</a>
                                                        </li>
                                                        <li v-if="record.ActiveCopy != 1 && record.ActivationSuspended==1">
                                                            <a @click="ResumeDB" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('GN0001269') }}</a>
                                                         </li>
                                                        <li v-else="record.ActiveCopy != 1 && record.ActivationSuspended!=1">
                                                            <a @click="SuspendDB" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('String601') }}</a>
                                                         </li>
                                                        <li v-if="record.ActiveCopy != 1">
                                                            <a @click="UpdateDB" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('GN0000654') }}</a>
                                                        </li>
                                                        <li v-if="record.ActiveCopy != 1">
                                                            <a @click="ActivateDB" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('GN0000807') }}</a>
                                                        </li>
                                                        <li v-if="showDeleteOption && record.ActiveCopy != 1">
                            
                                                            <a @click="confirmRemove(record.DatabaseName,record.MailboxServer)" :data-DBName="record.DatabaseName" :data-Server="record.MailboxServer" :data-DAGServers="record.DAGServers"
                                                              v-bind:class="'btnAction waves-effect waves-block'">{{ 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>
`

}