// utils/index.js

import Vue from 'vue';

// @ts-ignore
String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};

export const EventBus = new Vue();

export function isValidJwt(jwt: any) {
    if (!jwt || jwt.split('.').length < 3) {
        return false;
    }
    const data = JSON.parse(atob(jwt.split('.')[1]));
    const exp = new Date(data.exp * 1000);
    const now = new Date();
    return now < exp;
}

export function getRemainingJwtValiditySeconds(jwt: any) {
    if (!jwt || jwt.split('.').length < 3) {
        return false;
    }
    const data = JSON.parse(atob(jwt.split('.')[1]));
    const exp = new Date(data.exp * 1000);
    const diff = exp.getTime() - new Date().getTime();
    if (diff <= 0) {
        return 0;
    }
    return Math.round(diff / 1000 * 100) / 100;
}

export function isEmpty(str: string) {
    return (0 === str.length || !str.trim());
}

export function dictEmptyValToNull(dict: object): object {
    if (dict == null) return {};
    const newDict: { [key: string]: string | null | object; } = Object.assign({}, dict);
    for (const [key, value] of Object.entries(dict)) {
        if (typeof value === 'string') {
            if (isEmpty(value)) {
                newDict[key] = null;
            }
        } else if (value && value.constructor === Object) { // check if "dictionary"
            newDict[key] = dictEmptyValToNull(value);
        }
    }
    return newDict;
}
