import VueSelect from '/Components/Common/VueSelect.js?v=3.6'
import InputSearch from '/Components/Common/InputSearch.js?v=3.6'
import SearchPanel from '/Components/Common/SearchPanelWrapper.js?v=3.6'
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 { getLabelText, getStatusString } from '/Components/Common/utils.js?v=3.6'
import Loading from "/Components/Common/Loading.js?v=3.6"
import ScheduleDetail from '/Components/VPS/ScheduleDetail.js?v2.7'
import ModalPopUp from '/Components/Common/ModalPopUp.js?v=3.6'

export default {
    props: {
        readOnly: { type: Boolean, required: true },
        customerId: { type: String, required: true },
        isLoggedInAsCustomer: { type: Boolean, required: true },
        allowtoAddVM: { type: Boolean, required: true },
        sortPreference: { type: Object, required: true }
    },
    components: {
        SearchPanel,
        OperationsPanel,
        VueSelect,
        InputSearch,
        NoRecords,
        Pager,
        Loading,
        ScheduleDetail,
        ModalPopUp
    },

    data() {
        return {
            isLoading: true,
            searchContainerDivClass: "col-md-3 col-sm-6 col-xs-12",
            totalRecords: 0,
            records: [],
            owners: {},
            statuses: {
                "show": true, "initialValue": "-1", "items": [
                    { "text": getLabelText('SMI711'), "value": "-1" },
                    { "text": getLabelText('strEnabled'), "value": "1" },
                    { "text": getLabelText('strDisabled'), "value": "0" }
                ]
            },
            search: {
                selectedOwner: '',
                subscriptionId: '',
                clientId: (this.customerId != '0' ? this.customerId : ''),
                customerName: '',
                vmName: '',
                clientCompanyName: '',
                selectedStatus: '',
                strLabel: '',
                pageIndex: 1,
                pageSize: gridPageSize,
                sortExpression: 'VPSId',
                sortDir: 'Desc',
                updateSorting: false
            },
            //ScheduleId, VMId, AutoOn, OffTimeUtc, OnTimeUtc, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, IsActive, IsEnabled, DateCreatedUtc
            scheduleDetail: {
                scheduleId: 0,
                selectableCustomers: [],
                selectedCustomer: 0,
                selectableAccounts: [],
                selectedAccount: 0, //VPSId
                autoOn: false,
                onTimeHour: 0,
                onTimeMin: 0,
                onTimeClock: 'AM',
                offTimeHour: 0,
                offTimeMin: 0,
                offTimeClock: 'PM',
                selectableTimezones: [],
                selectedTimeZoneId: 26, //(GMT) Greenwich Mean Time: Dublin, Edinburgh, Lisbon, London
                isEnabled: true,
                days: { monday: true, tuesday: true, wednesday: true, thursday: true, friday: true, saturday: false, sunday: false }
            },
            showClearButton: false,
            showDetail: false,

            //***** START: Modal Popup *******
            showModal: false,
            modalTitle: '',
            yesText: '',
            noText: '',
            parentContext: {},  //params to execute callback method related to current operation
            scheduleLogs: []
        }
    },
    methods: {
        inputSearchChangeHandler: function (obj) {
            this.search[obj.fieldName] = obj.searchValue;
            this.showClearButton = obj.submit;

            if (obj.submit == true)
                this.doSearch();
        },
        getLabelText,
        getStatusString,
        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();
        },
        ownerChangeHandler: async function (obj) {

            this.search.selectedOwner = obj.selectedValue;
            setOwnerCookie(obj.selectedValue);

        },
        statusChangeHandler: function (obj) {
            this.search.selectedStatus = obj.selectedValue;
        },
        listOwners: async function () {

            var vm = this;

            await fetch("/webservices/machpanelservice.asmx/GetOwners", fetchGet)
                .then(response => response.json()).then((data) => {

                    vm.owners = JSON.parse(data.d);
                    this.search.selectedOwner = vm.owners.initialValue;

                })
                .catch(function (e) {
                    displayErrorMsg(e);
                });

        },
        listRecords: async function () {

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

            await fetch("/RCC/VPS/VPSAccounts.aspx/GetVPSSchedules", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.search.updateSorting = false;
                    vm.records = JSON.parse(data.d);
                    if (vm.records.length > 0)
                        this.totalRecords = this.records[0].Counter;
                });
            vm.isLoading = false;
            vm.showModal = false;
        },
        pagerChangeHandler: function (o) {
            this.search.pageIndex = o.pageIndex;
            this.search.pageSize = o.pageSize;
            this.doSearch();
        },
        doClearSearch: async function () {

            this.search.subscriptionId = '';
            this.search.clientId = (this.customerId != '0', this.customerId, '');
            this.search.customerName = '';
            this.search.vmName = '';
            this.search.clientCompanyName = '';
            this.search.selectedStatus = this.statuses.initialValue;
            this.search.strLabel = '';

            this.search.pageIndex = 1;

            updateSelectInterface();    //Required to update SOL control in case of html select.
            this.doSearch();
        },
        doSearch: function () {
            clearAllMsgs();
            var vm = this;
            this.listRecords().catch(function (e) {
                vm.records = [];
                vm.totalRecords = 0;
                vm.isLoading = false;
                vm.showModal = false;
                displayErrorMsg(e);
            });
        },
        getAccountStatus: function (s, IsSingleVM, SubStatus) {
            let Status = parseInt(s);
            // alert(SubStatus);
            if (SubStatus == 1) {
                if (Status == 1)
                    return this.getLabelText('GN0000222');
                else if (Status == 3)
                    return this.getLabelText('GN00001545');
                else if (Status == 4)
                    return this.getLabelText('GN0000348');
                else if (Status == 7 || Status == 0) //pending cancel or pending delete
                    return this.getLabelText('SPT002056');
                else if (Status == 8)
                    return this.getLabelText('SPT002057');
                else if (Status == 9)
                    return this.getLabelText('SPT002058');
                else if (IsSingleVM && Status == 10)
                    return this.getLabelText('GN0000222');
                else if (Status == 10)
                    return this.getLabelText('SPT002059');
                else
                    return '';
            }
            else if (SubStatus == 3)
                return this.getLabelText('GN00001545');
            else if (SubStatus == 4)
                return this.getLabelText('GN0000348');
            else if (SubStatus == 7 || Status == 0) //pending cancel or pending delete
                return this.getLabelText('SPT002056');
            else if (SubStatus == 8)
                return this.getLabelText('SPT002057');
            else if (SubStatus == 9)
                return this.getLabelText('SPT002058');
            else
                return '';

        },
        disableSchedule: async function (e) {
            let postRequest = { ...fetchPost };
            var param = {
                'scheduleId': e.target.dataset.id,
                'enable': 'false'
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/VPS/VPSAccounts.aspx/EnableSchedule", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d == true || data.d == 'true') {

                        this.doClearSearch();

                        displaySuccessMsg(this.getLabelText('EGN0000011'));
                    }

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        enableSchedule: async function (e) {
            let postRequest = { ...fetchPost };
            var param = {
                'scheduleId': e.target.dataset.id,
                'enable': 'true'
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/VPS/VPSAccounts.aspx/EnableSchedule", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d == true || data.d == 'true') {

                        this.doClearSearch();

                        displaySuccessMsg(this.getLabelText('EGN0000011'));
                    }

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        deleteSchedule: async function (e) {
            if (!confirm('are you sure to delete schedule for ' + e.target.dataset.vmname + ''))
                return;
            let postRequest = { ...fetchPost };
            var param = {
                'scheduleId': e.target.dataset.id
            };

            postRequest.body = JSON.stringify(param);

            fetch("/RCC/VPS/VPSAccounts.aspx/DeleteSchedule", postRequest)
                .then(response => response.json()).then((data) => {

                    if (data.d == true || data.d == 'true') {

                        this.doClearSearch();

                        displaySuccessMsg(this.getLabelText('EGN0000011'));
                    }

                }).catch(function (e) {
                    displayErrorMsg(e);
                });
        },
        viewHistory: async function (e) {

            var vm = this;
            vm.scheduleLogs = [];
            let postRequest = { ...fetchPost };
            let params = {
                "scheduleId": e.target.dataset.id
            }
            postRequest.body = JSON.stringify(params);

            await fetch("/RCC/VPS/VPSAccounts.aspx/GetScheduleLogs", postRequest)
                .then(response => response.json()).then((data) => {

                    vm.scheduleLogs = JSON.parse(data.d);
                    vm.showModal = true;
                    vm.parentContext = { op: "logs" };
                    vm.modalTitle = 'Logs History';

                }).catch(function (e) {
                    vm.scheduleLogs = [];
                    displayErrorMsg(e);
                });
        },
        newSchedule: async function () {
            this.showDetail = true;
        },
        scheduleSaveCancelled: function (obj) {
            this.showDetail = false;
        },
        
        scheduleSaveCompleted: function (obj) {
            this.showListing();
        },

        showListing: function () { this.showDetail = false; this.doClearSearch(); }
        
    },
    created: async function () {

        this.search.sortDir = this.sortPreference.SortDirection;
        this.search.sortExpression = this.sortPreference.SortExpression;
        this.search.selectedStatus = this.statuses.initialValue;

        var vm = this;

        await this.listOwners().then(this.listRecords).catch(function (e) {
            vm.records = [];
            vm.showModal = false;
            vm.totalRecords = 0;
            vm.isLoading = false;
            displayErrorMsg(e);
        });

    },
    template: '#vpsschedules-template'
}
