import OperationsPanel from '/Components/Common/OperationsPanelWrapper.js?v=3.4'
import Pager from '/Components/Common/Pager.js?v=3.4'
import NoRecords from '/Components/Common/NoRecords.js?v=3.4'
import VueSelect from '/Components/Common/VueSelect.js?v=3.4'
import { getLabelText } from '/Components/Common/utils.js?v=3.4'
import Loading from "/Components/Common/Loading.js?v=3.4"
import InputText from "/Components/Common/InputText.js?v=3.4"

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

            headerText: '',
            isAddEditMode: false,
            recordIdToEdit: '0',
            isEnabled: true,
            imageName: '',
            imagePath: '',
            rbGeneration: 2,
            rbCopyFile: 1,
            ddlSealedImageTypes: {},
            selectedSealedImageType: '',
            ddlOSName: {},
            selectedOSName: '',
            defaultUser: 'root',
            applyWindowsProductKey: false,
            delayforOS: 3,

        }
    },
    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/GetVPSSealedImages", 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;
        },        
        sealedImageTypeChangeHandler: function (obj) {
            this.selectedSealedImageType = obj.selectedValue;

            this.listOSName();
        },
        osNameChangeHandler: function (obj) {
            this.selectedOSName = obj.selectedValue;
        },
        listSealedImageTypes: async function () {

            var vm = this;

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

                    vm.ddlSealedImageTypes = JSON.parse(data.d);
                    vm.selectedSealedImageType = vm.ddlSealedImageTypes.initialValue;

                });

        },
        listOSName: async function () {

            var vm = this;

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

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

        },
        setAddEditUI: async function (editId) {
            this.clearAddEditForm();

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

            if (this.recordIdToEdit != '0') {
                this.headerText = this.getLabelText('HyperV11');
                await this.getRecordToEdit();
            }
            else
                this.headerText = this.getLabelText('HyperV07');
        },
        getRecordToEdit: async function () {
            var vm = this;
            var osname = '';
            let postRequest = { ...fetchPost };
            let params = {
                'Id': this.recordIdToEdit
            };
            postRequest.body = JSON.stringify(params);

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

                    if (data.d != null) {

                        vm.isEnabled = data.d.isEnabled;
                        vm.imageName = data.d.imageName;
                        vm.imagePath = data.d.imagePath;
                        vm.rbGeneration = data.d.rbGeneration;
                        vm.rbCopyFile = data.d.rbCopyFile;
                        vm.selectedSealedImageType = data.d.selectedSealedImageType;
                        osname = data.d.selectedOSName;
                        vm.defaultUser = data.d.defaultUser;
                        vm.applyWindowsProductKey = data.d.applyWindowsProductKey;
                        vm.delayforOS = data.d.delayforOS;
                    }
                }).catch(function (e) {
                    displayErrorMsg(e);
                });

            await this.listOSName();
            vm.selectedOSName = osname;
        },
        saveRecord: async function () {
            clearAllMsgs();
            if (this.imageName == '' || this.imagePath == '' || (this.selectedSealedImageType == 2 && this.defaultUser == '')) {
                displayErrorMsg(Error(this.getLabelText('strRequiredFieldsError')));
                return false;
            }

            var vm = this;

            let postRequest = { ...fetchPost };
            let params = {
                'SealedImageId': this.recordIdToEdit,
                'imageName': this.imageName,
                'isEnabled': this.isEnabled,
                'imagePath': this.imagePath,
                'rbGeneration': this.rbGeneration,
                'rbCopyFile': this.rbCopyFile,
                'selectedSealedImageType': this.selectedSealedImageType,
                'selectedOSName': this.selectedOSName,
                'defaultUser': this.defaultUser,
                'applyWindowsProductKey': this.applyWindowsProductKey,
                'delayforOS': this.delayforOS
            };
            postRequest.body = JSON.stringify(params);

            await fetch("/PCC/VPS/Setup.aspx/SaveVPSSealedImage", 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.isEnabled = true;
            this.imageName = '';
            this.imagePath = '';
            this.rbGeneration = 2;
            this.rbCopyFile = 1;
            //this.ddlSealedImageTypes = {};
            this.selectedSealedImageType = this.ddlSealedImageTypes.initialValue;
            //this.ddlOSName = {};
            this.selectedOSName = this.ddlOSName.initialValue;
            this.defaultUser = 'root';
            this.applyWindowsProductKey = false;
            this.delayforOS = 3;
        },
        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 this Image ?'))
                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/RemoveVPSSealedImage", 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.listSealedImageTypes).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('HyperV07') }}</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-2">{{ getLabelText('GN0001267') }}</th>
                                        <th class="col-xs-4">{{ getLabelText('GN0000282') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strSealedImageType') }}</th>
                                        <th class="col-xs-2">{{ getLabelText('strApplyWindowsProductKey') }}</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.SealedImageID)">{{ record.ImageName }}</a></td>
                                        <td>{{ record.ImagePath }}</td>
                                        <td>{{ record.SealedImageType }}</td>
                                        <td>{{ (record.ApplyWindowsProductKey ? getLabelText('Yes') : getLabelText('No')) }}</td>
                                        <td v-if="!readOnly">
                                            <a @click.prevent="setAddEditUI(record.SealedImageID)" class="btn btn-primary waves-effect">{{ getLabelText('GN0000276') }}</a>
                                            <a @click.prevent="confirmRemoveRecord" :data-id="record.SealedImageID" 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" style="display: none">
                                        <div class="col-sm-3 col-xs-12 row-label">{{ getLabelText('GN000195') }}</div>
                                        <div class="col-sm-4 col-xs-12">
                                            <input type="checkbox" v-model="isEnabled" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('GN0001267') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="imageName" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('GN0000282') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="imagePath" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strVMGeneration') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <label for="RdbGen2" class="radio-inline">
                                                    <input type="radio" id="RdbGen2" value="2" v-model="rbGeneration">&nbsp;{{getLabelText('strGeneration2')}}
                                                </label>
                                                <label for="RdbGen1" class="radio-inline">
                                                    <input type="radio" id="RdbGen1" value="1" v-model="rbGeneration">&nbsp;{{getLabelText('strGeneration1')}}
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strSealedImageType') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group form-float">
                                                <VueSelect :options="ddlSealedImageTypes.items" :selectedValue="selectedSealedImageType" @selectchange="sealedImageTypeChangeHandler" />
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row" id="trOS" runat="server">
                                        <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" v-show="selectedSealedImageType == 2">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strCopyVMFileMethod') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <div class="form-group">
                                                <label for="RdbLegacyCopyVMFile" class="radio-inline">
                                                    <input type="radio" id="RdbLegacyCopyVMFile" value="1" v-model="rbCopyFile">&nbsp;{{getLabelText('strLegacyCopyVMFile')}}
                                                </label>
                                                <label for="RdbNoCloudISO" class="radio-inline">
                                                    <input type="radio" id="RdbNoCloudISO" value="2" v-model="rbCopyFile">&nbsp;{{getLabelText('strNoCloudISO')}}
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row" v-show="selectedSealedImageType == 2">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strDefaultUser') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="defaultUser"/>
                                        </div>
                                    </div>
                                    <div class="row" v-show="selectedSealedImageType == 1">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strApplyWindowsProductKey') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <input type="checkbox" v-model="applyWindowsProductKey" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-sm-3 col-xs-12 row-label">* {{ getLabelText('strDelayforOS') }}: </div>
                                        <div class="col-sm-4 col-xs-12">
                                            <InputText v-model:fieldValue="delayforOS" />
                                        </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>
`
}
