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 { 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,
        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: 'LicenseKeyId',
                sortDir: 'Asc',
                updateSorting: false
            },

            headerText: this.getLabelText('strAddEditLicense'),
            isAddEditMode: false,
            recordIdToEdit: '0',
            license: '',
            ddlOSName: {},
            selectedOSName: '',
            numberofActivationsPossible: '',
            // numberofActivationsReadOnly: '2',
            numberOfActivationUsed: 0,
            isActive: false,
        }
    },
    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/GetOSLicenses", 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();
            }
        },
        osNameChangeHandler: function (obj) {
            this.selectedOSName = obj.selectedValue;
        },
        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/GetOSLicenseToEdit", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d != null) {
                        vm.isActive = data.d.isActive;
                        vm.license = data.d.license;
                        vm.numberofActivationsPossible = data.d.numberofActivationsPossible;
                        vm.numberofActivationsReadOnly = data.d.numberofActivationsReadOnly;
                        vm.numberOfActivationUsed = data.d.numberOfActivationUsed;
                        vm.selectedOSName = data.d.selectedOSName;
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        saveRecord: async function () {
            clearAllMsgs();
            // alert(this.license);
            if (this.license == '' || this.numberofActivationsPossible == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'LicenseKeyId': this.recordIdToEdit,
                'isActive': this.isActive,
                'license': this.license,
                'numberofActivationsPossible': this.numberofActivationsPossible,
                'selectedOSName': this.selectedOSName
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/Setup.aspx/SaveOSLicense", 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';
        },
        listOSName: async function () {

            var vm = this;

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

                    vm.ddlOSName = JSON.parse(data.d);
                    this.selectedOSName = vm.ddlOSName.initialValue;

                });

        },
        clearAddEditForm: function () {
            clearAllMsgs();

            this.isAddEditMode = false;
            this.recordIdToEdit = '0';
            this.license = '';
            this.selectedOSName = this.ddlOSName.initialValue;
            this.numberofActivationsPossible = '';
            // this.numberofActivationsReadOnly = '2';
            this.numberOfActivationUsed = 0;
            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/RemoveOSLicense", 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);
            });
        },
    },
    created: async function () {

        var vm = this;

        await this.listRecords().then(this.listOSName).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('strAddLicense') }}</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('strLicenseKey') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strOSVersion') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strNumberofActivationsPossible') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strNoActivationUsed') }}</th>
                                        <th class="col-xs-1">{{ getLabelText('strActive') }}</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.LicenseKeyId)">{{ record.LicenseKey }}</a></td>
                                        <td>{{ record.WindowsOSVersion }}</td>
                                        <td>{{ record.NumberofActivationsPossible }}</td>
                                        <td>{{ record.NoActivationUsed }}</td>
                                        <td>{{ (record.IsActive ? getLabelText('Yes') : getLabelText('No')) }}</td>
                                        <td v-if="!readOnly">
                                            <a @click.prevent="setAddEditUI(record.LicenseKeyId)" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a @click.prevent="confirmRemoveRecord" :data-id="record.LicenseKeyId" v-if="record.NoActivationUsed == 0 && record.NumberofActivationsReadOnlyUsed == 0" 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('strLicenseKey') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="license" :disabled="numberOfActivationUsed > 0" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('GN00001560') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group form-float">
                                                <VueSelect :options="ddlOSName.items" :selectedValue="selectedOSName" @selectchange="osNameChangeHandler" />
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strNumberofActivationsPossible') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="numberofActivationsPossible" />
                                        </div>
                                    </div>
                                     
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strActive') }}: </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">
                                            <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>
`
}
