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

export default {
    props: {
        readOnly: { type: Boolean, required: true }
    },
    components: {
        OperationsPanel,
        NoRecords,
        Pager,
        VueSelect,
        ModalPopUp,
        VueMultiSelectableSelected,
        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: 'PortRangeId',
                sortDir: 'Asc',
                updateSorting: false
            },

            headerText: this.getLabelText('strRDPCustomPortsRange'),
            isAddEditMode: false,
            recordIdToEdit: '0',
            portsRangeStart: '',
            portsRangeEnd: '',
            customers: [],
            selectedCustomers: [],
            isActive: false,

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: '',
            yesText: '',
            appliesToDetails: '',
            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();
        },
        fillCustomers: async function () {
            var vm = this;

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

                    if (data.d != null) {
                        vm.customers = data.d;
                    }
                });
        },
        selectionInfoHandler: function (selectableItems, selectedItems, id) {
            this.selectedCustomers = selectedItems;
        },
        listRecords: async function () {

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

            await fetch("/PCC/VPS/Setup.aspx/GetRDPCustomPorts", 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.recordIdToEdit = editId == '' ? '0' : editId;
            this.customers.clearSelection();

            if (this.recordIdToEdit != '0')
                await this.getRecordToEdit();
            else
                this.isAddEditMode = true;
        },
        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/GetRDPCustomPortToEdit", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.isActive = data.d.isActive;
                        vm.portsRangeStart = data.d.portsRangeStart;
                        vm.portsRangeEnd = data.d.portsRangeEnd;
                        vm.customers.setSelectedListByListOfVals(data.d.customers);

                        vm.isAddEditMode = true;
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        saveRecord: async function () {
            clearAllMsgs();
            if (this.portsRangeStart == '' || this.portsRangeEnd == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            if (this.portsRangeEnd < this.portsRangeStart) {
                displayErrorMsg(Error(this.getLabelText('strStartAndEndRange')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'VPSPortRangeId': this.recordIdToEdit,
                'isActive': this.isActive,
                'portsRangeStart': this.portsRangeStart,
                'portsRangeEnd': this.portsRangeEnd,
                'selectedCustomers': this.selectedCustomers
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/Setup.aspx/SaveRDPCustomPorts", 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.portsRangeStart = '';
            this.portsRangeEnd = '';
            this.isActive = false;
        },
        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;

            if (confirm('Are you sure you want to delete license key ?'))
                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/RemoveRDPCustomPort", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.doSearch();
                    displaySuccessMsg(this.getLabelText('EGN0000011'));

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        mpModelEventHandler: function (obj) {
            //if (obj.submit == true) {
            //    if (obj.parentContext.op == "convert") {
            //        this.convertToPaidSubscriptions(obj);
            //    }
            //}

            this.appliesToDetails = '';
            this.showModal = false;
        },
        showAppliesTo: function (c) {

            var vm = this;

            vm.appliesToDetails = c;
            vm.showModal = true;
            vm.parentContext = { op: "convert" };
            vm.modalTitle = this.getLabelText('SM200001');

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

        var vm = this;

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

        <div class="col-xs-12">
            <div class="card">
                <div class="body">

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

                            </div>
                        </div>
                    </ModalPopUp>

                    <div class="row" v-show="!isAddEditMode">

                        <OperationsPanel v-if="!readOnly">
                            <a @click="setAddEditUI('')" class="btn btn-primary waves-effect btnAction">{{ getLabelText('strAddRDPCustomPorts') }}</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('strPortsRange') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strStatus') }}</th>
                                        <th class="col-xs-5">{{ 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.PortRangeId)">{{ record.PortRangeStart + ' - ' + record.PortRangeEnd }}</a></td>
                                        <td>{{ (record.Enabled ? getLabelText('strEnabled') : getLabelText('strDisable')) }}</td>
                                        <td><a @click.prevent="showAppliesTo(record.Customers)"><span v-html="(record.Customers.length <= 110 ? record.Customers : record.Customers.substring(0, 110) + ' ... ')"></span></a></td>
                                        <td v-if="!readOnly">
                                            <a @click.prevent="setAddEditUI(record.PortRangeId)" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a @click.prevent="confirmRemoveRecord" :data-id="record.PortRangeId" 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('strPortsRange') }}: </div>
                                        <div class="col-sm-2 col-xs-12">
                                            <InputText v-model:fieldValue="portsRangeStart" fieldDataType="number" @change="if(this.portsRangeStart == ''){this.portsRangeStart = 0;}" />
                                        </div>
                                        <div class="col-sm-1 col-xs-12">-</div>
                                        <div class="col-sm-2 col-xs-12">
                                            <InputText v-model:fieldValue="portsRangeEnd" fieldDataType="number" @change="if(this.portsRangeEnd == ''){this.portsRangeEnd = 0;}" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strEnabled') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <input type="checkbox" v-model="isActive" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12 row-label">* {{ getLabelText('SMI0369') }}: </div>
                                        <div class="col-xs-12">
                                            <VueMultiSelectableSelected :useTranslation="true" :items="customers" id="customers" @selectionInfo="selectionInfoHandler" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <a v-if="!readOnly" @click.prevent="saveRecord" class="btn btn-primary waves-effect btnAction">{{ getLabelText('GN0000281')}} </a>
                                            <a @click.prevent="cancelRecord" class="btn btn-primary waves-effect">{{ getLabelText('GN0000572')}} </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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