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 SearchPanel from '/Components/Common/SearchPanelWrapper.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: {
        readOnly: { type: Boolean, required: true },
    },
    components: {
        OperationsPanel,
        SearchPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        Loading
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            serverGroupObj: {},

            search: {
                selectedOwner: '',
                serverGroupId: '-1',
                customerId: '',
                customerName: '',
                serverName: '',
                serverIP: '',

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

            if (obj.submit == true)
                this.doSearch();
        },
        ownerChangeHandler: async function (obj) {

            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);

        },
        serverGroupChangeHandler: async function (obj) {

            this.search.serverGroupId = obj.selectedValue;

        },
        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();
        },
        listOwners: async function () {

            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/GetOwners", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.owners = JSON.parse(data.d);
                    this.search.selectedOwner = vm.owners.initialValue;

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

        },
        listRecords: async function () {

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

            await fetch("/PCC/VPS/ServerGroups.aspx/GetVPSCustomerToServerMappings", 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, showMore: false }));
                });

            vm.isLoading = false;
        },
        getServerGroup: async function () {

            var vm = this;

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

                    vm.serverGroupObj = JSON.parse(data.d);
                    this.search.serverGroupId = vm.serverGroupObj.initialValue;
                });

        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {
            this.search.serverGroupId = '-1';
            this.search.customerId = '';
            this.search.customerName = '';
            this.search.serverName = '';
            this.search.serverIP = '';            

            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('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);
                });
        },
        
    },
    created: async function () {

        var vm = this;

        await this.listOwners().then(vm.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/ManageServerMappings.aspx'" class="btn btn-primary waves-effect btnAction">{{ getLabelText('AddCustomerServerMappings') }}</a>
                         </OperationsPanel>

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

                            <div :class="searchContainerDivClass" v-if="owners.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="owners.items" :selectedValue="this.search.selectedOwner" @selectchange="ownerChangeHandler" />
                                </div>
                            </div>

                            <div :class="searchContainerDivClass" v-if="serverGroupObj.show">
                                <div class="form-group form-float">
                                    <VueSelect :options="serverGroupObj.items" :selectedValue="this.search.serverGroupId" @selectchange="serverGroupChangeHandler" />
                                </div>
                            </div>

                            <InputSearch :searchValue="search.customerId" fieldName="customerId" fieldDataType="Number" :fieldLabel="getLabelText('GN0000715')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.customerName" fieldName="customerName" :fieldLabel="getLabelText('GN0000268')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.serverName" fieldName="serverName" :fieldLabel="getLabelText('GN0000980')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />
                            <InputSearch :searchValue="search.serverIP" fieldName="serverIP" :fieldLabel="getLabelText('GN0001203')" :containerDivClass="searchContainerDivClass" @inputSearchChange="inputSearchChangeHandler" />

                        </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('GN0000980')}}</th>
                                        <th class="col-xs-2">{{ getLabelText('GN0001203') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('GN0000971') }}</th>
                                        <th class="col-xs-5">{{ getLabelText('DEV1133') }}</th>
                                        <th class="col-xs-1 align-center">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                        <td>{{ record.ServerName }}</td>
                                        <td>{{ record.IP }}</td>
                                        <td>{{ record.ServerGroupName }}</td>
                                        <td>
                                            <span v-if="record.showMore || record.Customers.length <= 100">{{ record.Customers.replaceAll(',', ', ') }}</span>
                                            <span v-else>{{ record.Customers.replaceAll(',', ', ').slice(0, 100) + '...' }}</span>
                                            <br/><a v-if="record.Customers.length > 100" href="#" @click.prevent="record.showMore = !record.showMore" class="btn btn-primary btn-sm">
                                                {{ record.showMore ? getLabelText('ShowLess') : getLabelText('ShowMore') }}
                                            </a>
                                        </td>
                                        <td>
                                            <a class="btn btn-primary waves-effect" v-bind:href="'/PCC/VPS/ManageServerMappings.aspx?SGMemId=' + record.VPSServerId + '&SGid=' + record.VPSServerGroupID">{{ getLabelText('GN0000276') }}</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>
`
}
