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 },
        addEditDTO: { type: Object, 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',
            ddlOSName: {},
            recordDTO: this.addEditDTO,

            //license: '',            
            //selectedOSName: '',
            //selectedOSNameText: '',
            //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.recordDTO.LicenseKeyId = editId == '' ? 0 : editId;

            if (this.recordDTO.LicenseKeyId != 0) {
                await this.getRecordToEdit();
            }
            else {
                this.recordDTO.SelectedOSId = this.ddlOSName.initialValue;
                this.recordDTO.SelectedOSName = this.ddlOSName.items.find(item => item.value === this.recordDTO.SelectedOSId)?.text || '';
            }
        },
        getRecordToEdit: async function () {
            var vm = this;

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

            await fetch("/PCC/VPS/Setup.aspx/GetOSLicenseToEdit", postRequest)
                .then(response => response.json()).then((data) => {
                    //console.log(data.d);

                    if (data.d != null) {
                        vm.recordDTO = data.d;

                        //var resp = data.d; // JSON.parse(data.d);

                        //vm.isActive = resp.isActive;
                        //vm.license = resp.license;
                        //vm.numberofActivationsPossible = resp.numberofActivationsPossible;
                        ////vm.numberofActivationsReadOnly = resp.numberofActivationsReadOnly;
                        //vm.numberOfActivationUsed = resp.numberOfActivationUsed;
                        //vm.selectedOSName = resp.selectedOSName;
                        //vm.selectedOSNameText = vm.ddlOSName.items.find(item => item.value === vm.selectedOSName)?.text || '';
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        saveRecord: async function () {
            clearAllMsgs();
            // alert(this.license);
            if (this.recordDTO.LicenseKey == '' || this.recordDTO.NumberOfActivationsPossible == '') {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'recordDTO': this.recordDTO
                //'LicenseKeyId': this.recordIdToEdit,
                //'isActive': this.isActive,
                //'license': this.license,
                //'numberofActivationsPossible': this.numberofActivationsPossible,
                //'selectedOSName': this.selectedOSName,
                //'selectedOSNameText': this.selectedOSNameText
            };
            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();
        },
        clearAddEditForm: function () {
            clearAllMsgs();
            var vm = this;
            vm.recordDTO = this.addEditDTO;

            this.isAddEditMode = false;
            //this.recordIdToEdit = '0';
            //this.license = '';
            //this.selectedOSName = this.ddlOSName.initialValue;
            //vm.selectedOSNameText = vm.ddlOSName.items.find(item => item.value === vm.selectedOSName)?.text || '';
            //this.numberofActivationsPossible = '';
            //// this.numberofActivationsReadOnly = '2';
            //this.numberOfActivationUsed = 0;
            //this.isActive = false;
        },
        osNameChangeHandler: function (obj) {
            this.recordDTO.SelectedOSId = obj.selectedValue;
            this.recordDTO.SelectedOSName = obj.selectedText;
        },
        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);
                    vm.recordDTO.SelectedOSId = vm.ddlOSName.initialValue;
                    vm.recordDTO.SelectedOSName = vm.ddlOSName.items.find(item => item.value === vm.recordDTO.SelectedOSId)?.text || '';
                });

        },
        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 license key "${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/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" :data-name="record.LicenseKey" 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="recordDTO.LicenseKey" :disabled="recordDTO.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="recordDTO.SelectedOSId" @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="recordDTO.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="recordDTO.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>
`
}
