//TODO: 1-graph of first tab issue in on selection of this tab

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

export default {

    props: {
        readOnly: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true },
        showDeleteOption: { type: Boolean, required: true },
    },
    components: {
        OperationsPanel,
        VueSelect,
        InputSearch,
        InputText,
        SearchPanel,
        NoRecords,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            serverGroups: {},
            records: [],
            search: {
                selectedServerGroup: '',
            },
            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.toString();
             

        },
        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.toString();                  
                });

        },
        listRecords: async function () {

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

            $('.page-loader-wrapper').show();

            await fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/FillDatabases", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                });
            vm.isLoading = false;
        },
        getAvgMailboxSize: async function () {

            var vm = this;

            await fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/GetAvgMailboxSize", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.doSearch();

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

        },
        getAvgMailboxSizeOfDB: function (dbName,servergroupid) {

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

                'DBname': dbName,
                'ServerGroupId': servergroupid
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/GetAvgMailboxSizeOfDB", postRequest)
                .then(response => response.json()).then((data) => {
                    //  alert(data.d);
                    //if (data.d == true || data.d == 'true') {
                    this.doSearch();
                    displaySuccessMsg(data.d); //

                    //}

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

        },
        openMBTab: function (e) {


            let dbName = e.target.dataset.dbname;
            let serverGroupId = e.target.dataset.servergroupid;

            this.$emit('onOpenMBTab', { DBName: dbName, ServerGroupId: serverGroupId });
        },
        openArchTab: function (e) {


            let dbName = e.target.dataset.dbname;
            let serverGroupId = e.target.dataset.servergroupid;

            this.$emit('onOpenArchTab', { DBName: dbName, ServerGroupId: serverGroupId });
        },
        getLabelText,       
        confirmRemove: function (dbName, servergroupid) {

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

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

                'DBname': dbName,
                'ServerGroupId': servergroupid
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/RemoveDB", postRequest)
                .then(response => response.json()).then((data) => {
                    //  alert(data.d);
                    //if (data.d == true || data.d == 'true') {
                    this.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011')); //

                    //}

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

        },
        doClearSearch: async function () {

            this.search.templateName = '';            

            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);
            });

        },
        saveDataBases: async function () {
            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                data: {
                    selectedItems: vm.records.map(it => ({
                        "ServerGroupId": it.ServerGroupId,
                        "DBName": it.DBName,
                        "MaxMailBoxes": it.MaxMailBoxes
                    })),
                }
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/Exchange/ExchDatabasesCopy.aspx/SaveDataBases", postRequest)
                .then(response => response.json()).then((data) => {
                    this.doSearch();
                    displaySuccessMsg(data.d);

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
    },
    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);
        });

        if (vm.records.length > 0) {
            setTimeout(function () {
                $('.page-loader-wrapper').show();
                DBSizeGraph(vm.records[0].DataForGraph, 'red'); MailBoxesInDBs(vm.records[0].DataForMailBoxesInDB);
                $('.page-loader-wrapper').hide();
            }, 100)
        };

    },
    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>
                        <a  @click="getAvgMailboxSize()" class="btn btn-primary waves-effect btnAction">{{ getLabelText('strSyncMailboxAvgSize') }}</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" id="divGraph" v-if="records.length > 0">
                        <div class="col-xs-6">
                            <h4 class="text-center">{{getLabelText("strDatabaseSizeonDisk")}}</h4>
                            <div id="graph"></div>
                            <pre id="code" class="prettyprint linenums"></pre>
                        </div>
                        <div class="col-xs-6">
                            <h4 class="text-center">{{getLabelText("strMailboxesAllocationOnDatabases")}}</h4>
                            <div id="graph2"></div>
                            <pre id="code2" class="prettyprint linenums"></pre>
                        </div>
                    </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"> {{getLabelText("SPT002073")}}</th>
                                    <th class="col-xs-1">{{getLabelText("strDatabaseSizeonDisk")}}</th>
                                    <th class="col-xs-1">{{getLabelText("DGN1110254")}}</th>
                                    <th class="col-xs-1">{{getLabelText("Mounted")}}</th>                                   
                                    <th class="col-xs-1"> {{getLabelText("Recovery")}}</th>
                                    <th class="col-xs-2"> {{getLabelText("DGN1110406")}}</th>
                                    <th class="col-xs-1"> {{getLabelText("strArchiveMailboxes")}}</th>
                                    <th class="col-xs-1"> {{getLabelText("GN0000360")}}</th>
                                </tr>
                                <tr v-for="record in records">
                                    <td>{{record.DBName}}</td>
                                    <td>{{record.AvgMailBoxSize}}  MB</td>
                                    <td >{{record.ExServerName}}</td>
                                    <td>{{record.Mounted}}</td>
                                    <td v-if="record.IsRecovery">{{getLabelText("strYes")}}</td>
                                    <td v-else>{{getLabelText("strNo")}}</td>
                                    <td>
                                        <table class="table small">
                                            <tbody>
                                                <tr>
                                                    <td class="col-xs-4 row-label">
                                                        {{getLabelText("strCurrent")}}:                                                            
                                                    </td>
                                                    <td class="col-xs-8">
                                                       <a @click.prevent="openMBTab" :data-servergroupId="record.ServerGroupId" :data-dbname="record.DBName">{{record.MBsCount}}</a>                                                                     
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="col-xs-4 row-label">
                                                          {{getLabelText("strMax")}}:                                                          
                                                    </td>
                                                    <td class="col-xs-8">
                                                        <InputText v-model:fieldValue="record.MaxMailBoxes" />
                                                    </td>
                                                </tr>
                                                <tr >
                                                    <td class="col-xs-4 row-label">
                                                        {{getLabelText("strAverageMailboxSize")}} 
                                                    </td>
                                                    <td class="col-xs-8">
                                                        {{record.AvgMailBoxSize}} MB
                                                    </td>
                                                </tr>
                                                                
                                            </tbody>
                                        </table>
                                    </td>
                                    <td v-if="record.ArchiveLoad > 0">
                                        <a @click.prevent="openArchTab" :data-servergroupId="record.ServerGroupId" :data-dbname="record.DBName">{{record.ArchiveLoad}}</a>                                                                     
                                    </td>
                                    <td v-else>
                                        {{record.ArchiveLoad}}
                                    </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>
                                                        <a @click="" :data-DBName="record.DBName" :data-ServerGroupId="record.ServerGroupId" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('GN0000276') }}</a>
                                                        </li>
                                                    <li>
                                                        <a @click="getAvgMailboxSizeOfDB(record.DBName,record.ServerGroupId)" v-bind:class="'btnAction waves-effect waves-block'">{{ getLabelText('strAverageMailboxSize') }}</a>
                                                    </li>
                                                        
                                                    <li v-if="showDeleteOption">
                            
                                                        <a @click="confirmRemove(record.DBName,record.ServerGroupId)" 
                                                            v-bind:class="[{'disabled':(record.MBsCount!=0 && record.MaxMailBoxes!=0)}, 'btnAction waves-effect waves-block']">{{ getLabelText('GN0000278') }}</a>
                                                    </li>                                                         
                                                </ul>    
                                            </li>
                                        </ul>
                                    </td>
                                </tr>
                                <tr>
                                </tr>

                            </tbody>
                        </table>
                        <NoRecords v-else />
                    </div>
                    <div class="col-xs-12">
                        <a @click.prevent="saveDataBases" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000281') }}</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
`

}