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 VueSelect from '/Components/Common/VueSelect.js?v=3.9'
import { getLabelText } from '/Components/Common/utils.js?v=3.9'
import Loading from "/Components/Common/Loading.js?v=3.9"
import InputText from "/Components/Common/InputText.js?v=3.9"

export default {
    props: {
        readOnly: { type: Boolean, required: true }
    },
    components: {
        OperationsPanel,
        NoRecords,
        Pager,
        VueSelect,
        Loading,
        InputText
    },
    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            search: {

                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'TierId',
                sortDir: 'Asc',
                updateSorting: false
            },
            noticeMsg: 'Max Mbps value must be greater then min Mbps.',
            headerText: this.getLabelText('strAddEditTier'),
            isAddEditMode: false,
            recordIdToEdit: '0',
            tierName: '',
            minMbps: '',
            maxMbps: '',
            tierPublicPrivate: '1',
        }
    },
    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/Setup.aspx/GetVNICBandwidthTiers", 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[0].TotalRecords;
                    }
                });
            vm.isLoading = false;
        },
        setAddEditUI: async function (editId) {
            this.clearAddEditForm();

            this.isAddEditMode = true;
            this.recordIdToEdit = editId == '' ? '0' : editId;

            if (this.recordIdToEdit != '0') {
                await this.getRecordToEdit();
            }
        },
        getRecordToEdit: async function () {
            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'Id': this.recordIdToEdit
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/Setup.aspx/GetVNICBandwidthTierToEdit", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.tierName = data.d.tierName;
                        vm.minMbps = data.d.minMbps;
                        vm.maxMbps = data.d.maxMbps;
                        vm.tierPublicPrivate = data.d.tierPublicPrivate;
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        saveRecord: async function (applyTire) {
            clearAllMsgs();
            if (this.tierName == '' || this.minMbps == '' || this.maxMbps == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            if (this.minMbps > this.maxMbps) {
                displayErrorMsg(Error(this.noticeMsg));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'TierId': this.recordIdToEdit,
                'tierName': this.tierName,
                'minMbps': this.minMbps,
                'maxMbps': this.maxMbps,
                'tierPublicPrivate': this.tierPublicPrivate,
                'applyTire': applyTire
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/Setup.aspx/SaveVNICBandwidthTier", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.cancelRecord();
                    vm.search.pageIndex = 1;
                    vm.doSearch();
                    displaySuccessMsg(data.d);
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        cancelRecord: function () {
            this.clearAddEditForm();
            this.search.pageIndex = 1;
            this.doSearch();
            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
            this.tierName = '';
            this.minMbps = '';
            this.maxMbps = '';
            this.tierPublicPrivate = '1';
        },
        confirmRemoveRecord: function (e) {
            // Get the value of the disabled attribute
            const disabledValue = e.target.getAttribute('disabled');

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

            let imageId = e.target.dataset.id;
            let name = e.target.dataset.name;

            if (confirm(`Are you sure you want to delete the VNIC bandwidth tier "${name}"?`))
                this.removeRecord(imageId);
        },
        removeRecord: function (Id) {
            var vm = this;
            let postRequest = { ...fetchPost };
            var param = {
                'Id': Id
            };

            postRequest.body = JSON.stringify(param);

            fetch("/PCC/VPS/Setup.aspx/RemoveVNICBandwidthTier", postRequest)
                .then(response => response.json()).then((data) => {
                    vm.search.pageIndex = 1;
                    vm.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011'));

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doSearch: function () {

            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                displayErrorMsg(e);
            });
        },
        alertMsg: function (msg) {
            alert(msg);
        }
    },
    created: async function () {

        var vm = this;

        await this.listRecords().catch(function (e) {
            vm.records = [];
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });
    },
    updated: function () {
        updateSelectInterface();
        AdminBSBThemeChanges();
    },
    template: `

        <div class="col-xs-12">
            <div class="card">
                <div class="body">
                    <div class="row" v-show="!isAddEditMode">

                        <OperationsPanel v-if="!readOnly">
                            <a @click="setAddEditUI('')" class="btn btn-primary waves-effect btnAction">{{ getLabelText('strAddBandWidthTier') }}</a>
                        </OperationsPanel>

                        <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" cellspacing="0" rules="all" border="1" v-if="records.length > 0">

                                <tbody>
                                    <tr>
                                        <th class="col-xs-3">{{ getLabelText('strTierName') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strMinMbps') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strMaxMbps') }}</th>
                                        <th class="col-xs-3">{{ getLabelText('strAppliedTo') }}</th>
                                        <th class="col-xs-2 align-center" v-if="!readOnly">{{ getLabelText('GN0000360') }}</th>
                                    </tr>
                                    <tr v-for="record in records">
                                        <td><a @click.prevent="setAddEditUI(record.TierId)">{{ record.TierName }}</a></td>
                                        <td>{{ record.MinMbps }}</td>
                                        <td>{{ record.MaxMbps }}</td>
                                        <td>{{ (record.AppliedTo == 1 ? 'Public NIC' : 'Private NIC') }}</td>
                                        <td v-if="!readOnly">
                                            <a @click.prevent="setAddEditUI(record.TierId)" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a @click.prevent="confirmRemoveRecord" :data-id="record.TierId" :data-name="record.TierName" class="btn btn-primary waves-effect btnAction" >{{ getLabelText('GN0000278') }}</a>
                                        </td>
                                    </tr>

                                    <Pager :totalRecords="totalRecords" :pageSize="this.search.pageSize" :currentPage="this.search.pageIndex" @pagerChange="pagerChangeHandler" />
                                </tbody>
                            </table>

                            <NoRecords v-else />

                        </div>
                    </div>



                    <div class="row" v-if="isAddEditMode">
                        <div class="col-xs-12">
                            <div class="card">
                                <div class="header">
                                    <h3 v-html="headerText"></h3>
                                </div>
                                <div class="body">
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strTierName') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="tierName" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strMinMbps') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText id="minMbps1" v-model:fieldValue="minMbps" fieldDataType="number" @Change="if(this.minMbps == ''){this.minMbps = 0;}" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strMaxMbps') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText id="maxMbps1" v-model:fieldValue="maxMbps" fieldDataType="number" @Change="if(this.maxMbps == ''){this.maxMbps = 0;}" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strAppliedTo') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <label for="RdbPublicTier" class="radio-inline">
                                                    <input :disabled="recordIdToEdit > 0" type="radio" id="RdbPublicTier" value="1" v-model="tierPublicPrivate">&nbsp;{{getLabelText('strPublicTier')}}
                                                </label>
                                                <label for="RdbPrivateTier" class="radio-inline">
                                                    <input :disabled="recordIdToEdit > 0" type="radio" id="RdbPrivateTier" value="2" v-model="tierPublicPrivate">&nbsp;{{getLabelText('strPrivateTier')}}
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <a v-if="!readOnly" @click.prevent="saveRecord(false)" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000281')}} </a>
                                            <a v-if="!readOnly" @click.prevent="saveRecord(true)" class="btn btn-primary waves-effect btnAction">{{ getLabelText('btnSaveAndApply')}} </a>
                                            <a @click.prevent="cancelRecord" class="btn btn-primary waves-effect">{{ getLabelText('GN0000572')}} </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
`
}
