export default {
    computed: {
        getBsVersion: function () {
            try {
                let getBsVersion = jQuery.fn.tooltip.Constructor.VERSION.split('.').shift();

                if (getBsVersion && getBsVersion !== '') {
                    return parseInt(getBsVersion);
                }
            } catch (e) {
                return 4;
            }

            return 4;
        },
    },

    methods: {
        openModal(refName, arg1, arg2, timeout) {
            let timeoutOnRefs = ['showPasswordAfterInstall'];

            // fix for lagom theme. lagom has an animation on modal open/close that makes the next modal invisible if opened when another modal is closing
            if (timeout && timeoutOnRefs.includes(refName) && this.getUsedTemplate() === 'lagom') {
                setTimeout(() => {
                    this.$refs[refName].open(arg1, arg2);
                }, timeout);
            } else {
                this.$refs[refName].open(arg1, arg2);
            }
        },

        getUsedTemplate() {
            if (this.$simpleStore.getSystemTheme().includes('lagom')) {
                return 'lagom';
            }

            return 'default';
        },

        dCan(requiredPermission) {
            let permissions = this.$simpleStore.getUserPermissions();

            if (!permissions || !Array.isArray(permissions)) {
                return false;
            }

            return !!permissions.includes(requiredPermission);
        },

        faIconRepo(icon) {
            let iconMap = {
                5: {
                    'fa-check': 'far fa-check',
                    'fa-check-circle': 'far fa-check-circle',
                    'fa-ban': 'far fa-ban',
                    'fa-key': 'far fa-key',
                    'fa-eye': 'fal fa-eye',
                    'fa-eye-slash': 'fal fa-eye-slash',
                    'fa-refresh': 'fal fa-sync',
                    'fa-refresh-spin': 'fal fa-sync fa-spin',
                    'fa-power-off': 'far fa-power-off',
                    'fa-plug': 'fas fa-plug',
                    'fa-play': 'far fa-play',
                    'fa-arrow-circle-up': 'fas fa-arrow-circle-up',
                    'fa-shopping-cart': 'fas fa-shopping-cart',
                    'fa-times': 'far fa-times',
                    'fa-times-circle': 'far fa-times-circle',
                    'fa-info-circle': 'far fa-info-circle',
                    'fa-exclamation-triangle': 'fas fa-exclamation-triangle',
                    'fa-sign-in': 'far fa-sign-in',
                    'fa-clock': 'far fa-clock',
                    'fa-plus': 'far fa-plus',
                    'fa-trash': 'far fa-trash',
                    'fa-calendar-alt': 'far fa-calendar-alt',
                    'fa-chart-area': 'fas fa-chart-area',
                    'fa-undo': 'far fa-undo',
                    'fa-angle-right': 'far fa-angle-right',
                    'fa-hdd': 'far fa-hdd',
                    'fa-database': 'far fa-database',
                    'fa-level-up-90': 'far fa-level-up fa-rotate-90',
                },
                4: {
                    'fa-check': 'fa fa-check',
                    'fa-check-circle': 'fa fa-check-circle',
                    'fa-ban': 'fa fa-ban',
                    'fa-key': 'fa fa-key',
                    'fa-eye': 'fa fa-eye',
                    'fa-eye-slash': 'fa fa-eye-slash',
                    'fa-refresh': 'fa fa-refresh',
                    'fa-refresh-spin': 'fa fa-refresh fa-spin',
                    'fa-power-off': 'fa fa-power-off',
                    'fa-plug': 'fa fa-plug',
                    'fa-play': 'fa fa-play',
                    'fa-arrow-circle-up': 'fa fa-arrow-circle-up',
                    'fa-shopping-cart': 'fa fa-shopping-cart',
                    'fa-times': 'fa fa-times',
                    'fa-times-circle': 'fa fa-times-circle',
                    'fa-info-circle': 'fa fa-info-circle',
                    'fa-exclamation-triangle': 'fa fa-exclamation-triangle',
                    'fa-sign-in': 'fa fa-sign-in',
                    'fa-clock': 'fa fa-clock-o',
                    'fa-plus': 'fa fa-plus',
                    'fa-trash': 'fa fa-trash',
                    'fa-calendar-alt': 'fa fa-calendar',
                    'fa-chart-area': 'fa fa-area-chart',
                    'fa-undo': 'fa fa-undo',
                    'fa-angle-right': 'fa fa-angle-right',
                    'fa-hdd': 'fa fa-hdd',
                    'fa-database': 'fa fa-database',
                    'fa-level-up-90': 'fa fa-level-up fa-rotate-90',
                }
            };

            return iconMap[faIconsVersion][icon];
        },

        generateRandomPassword(length = 10) {
            const wishlist = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~?-_*+'";

            const generatePassword = Array.from(crypto.getRandomValues(new Uint32Array(length)))
                .map((x) => wishlist[x % wishlist.length])
                .join('');

            return generatePassword.substr(0, length);
        },

        async getUserAccount() {
            try {
                let data = await axios.get(this.xhrUrl + 'getUserAccount');
                let userAccountDetails = data.data;

                this.$simpleStore.setUserPermissions(userAccountDetails.permissions);
                this.$simpleStore.setUserAccountData(userAccountDetails);
            } catch (e) {
                return false;
            }
        },

        async executeInstallationPostAction() {
            this.$simpleStore.addLoader('executeInstallationPostAction');

            try {
                let data = await axios.get(this.xhrUrl + 'executeInstallationPostAction');
                return data.data;
            } catch (e) {
                this.errorNotificationFlash(e.response.data);
            } finally {
                this.$simpleStore.delLoader('executeInstallationPostAction');
            }
        },

        jsToLang: (search) => {
            return search.split(".").reduce((r, k) => r?.[k], dServermanagerLanguage)
        },

        sleeper(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        },

        truncateLong(string, length) {
            if (!string) {
                return '';
            }
            return (string.length > length) ? `${string.substring(0, length)}…` : string
        },

        formatByteToNice(bytes, decimals = 2, isMb, isKb, returnStringIfNull = '0 Bytes', customSizes = null, useBase1000 = false) {
            if (bytes === null || bytes === undefined || isNaN(bytes) || bytes === 0) {
                return returnStringIfNull;
            }

            if (decimals === '') {
                decimals = 2;
            }

            let k = useBase1000 ? 1000 : 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = customSizes || [
                'Bytes',
                'KB',
                'MB',
                'GB',
                'TB',
                'PB',
                'EB',
                'ZB',
                'YB'
            ];

            if (isMb && !customSizes) {
                if (isMb === 'mib') {
                    bytes *= 1024 * 1024;
                    k = 1000;
                } else {
                    sizes.splice(0, 2);
                }
            }

            if (isKb && !customSizes) {
                sizes.splice(0, 1);
            }

            const i = Math.floor(Math.log(bytes) / Math.log(k));

            const validIndex = Math.max(0, Math.min(i, sizes.length - 1));

            return parseFloat((bytes / Math.pow(k, validIndex)).toFixed(dm)) + ' ' + sizes[validIndex];
        },

        errorNotificationFlash(msg, onlyHandleErrorNoFlash = false, noException = false) {
            if (!onlyHandleErrorNoFlash) {
                this.$toast.error(msg, {
                    pauseOnFocusLoss: false,
                    draggable: false,
                    closeOnClick: false,
                });
            }

            if (!noException) {
                throw msg;
            }
        },

        successNotificationFlash(msg) {
            this.$toast.success(msg, {
                position: 'top-right',
                pauseOnFocusLoss: false,
            });
        },

        convertDateTime(timestamp) {
            if (!timestamp) {
                return '-';
            }

            let date;

            if (typeof timestamp === 'number' || /^\d+$/.test(timestamp)) {
                date = new Date(parseInt(timestamp) * 1000);
            } else {
                date = new Date(timestamp);
            }

            if (isNaN(date.getTime())) {
                return '-';
            }

            return date.toLocaleString();
        },

        async refsProxy(refs, methodName, args, withAwait) {
            if (refs && methodName in refs && typeof refs[methodName] === 'function') {
                if (args) {
                    return withAwait ? await refs[methodName](...args) : refs[methodName](...args)
                } else {
                    return withAwait ? await refs[methodName]() : refs[methodName]()
                }
            }
        },

        async featureAvailabilityChecker(feature) {
            if (feature === 'getServerBackupsAvailable' || feature === 'getServerSnapshotsAvailable') {
                let data = await axios.get(this.xhrUrl + feature);

                return data.data;
            }
        }
    }
}