export function decodeJWTPayload(token) {
    var _a = token.split('.'), payloadStr = _a[1];
    return JSON.parse(atob(payloadStr));
}
export function isExpiredJWT(token) {
    var exp = decodeJWTPayload(token).exp;
    return isExpiredInSeconds(exp || 0, 60); // exp or always, and 1 minute earlier
}
export function ApiError(result) {
    this.name = 'ApiError';
    this.message = result.message;
    this.error = result;
}
export function isExpiredInSeconds(expiredTime, costMore) {
    if (costMore === void 0) { costMore = 0; }
    var time = Math.ceil(new Date().getTime() / 1000) + costMore;
    return time >= expiredTime;
}
// create popup
export function createPopup(config) {
    var url = config.url || '/';
    var name = config.name || 'SheetbaseOAuthLogin'; // no space for IE
    var options = config.options || ('location=0,status=0' +
        ',width=' + window.innerWidth +
        ',height=' + window.innerHeight);
    var callback = config.callback || (function () { return true; });
    // launch window
    var oauthWindow = window.open(url, name, options);
    // cackback
    var oauthInterval = window.setInterval(function () {
        if (oauthWindow.closed) {
            window.clearInterval(oauthInterval);
            callback();
        }
    }, 1000);
}
// get app host
export function getHost() {
    var host;
    // get from base tag
    // else from window.location.href
    var baseHref = ((document.getElementsByTagName('base')[0] || {})['href'] || '').slice(0, -1);
    if (!!baseHref) {
        host = baseHref;
    }
    else {
        var hrefSplit = window.location.href.split('/').filter(Boolean);
        host = hrefSplit[0] + '//' + hrefSplit[1];
    }
    return host;
}
// convert string of data load from spreadsheet to correct data type
export function parseData(data) {
    if ((data + '').toLowerCase() === 'true') {
        // boolean TRUE
        data = true;
    }
    else if ((data + '').toLowerCase() === 'false') {
        // boolean FALSE
        data = false;
    }
    else if (!isNaN(data)) {
        // number
        data = Number(data);
    }
    else if ((data.substr(0, 1) === '{' && data.substr(-1) === '}') ||
        (data.substr(0, 1) === '[' && data.substr(-1) === ']')) {
        // JSON
        try {
            data = JSON.parse(data);
        }
        catch (e) {
            // continue
        }
    }
    return data;
}
export function parseObject(obj) {
    for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {
        var key = _a[_i];
        if (obj[key] === '' || obj[key] === null || obj[key] === undefined) {
            // delete null key
            delete obj[key];
        }
        else if ((obj[key] + '').toLowerCase() === 'true') {
            // boolean TRUE
            obj[key] = true;
        }
        else if ((obj[key] + '').toLowerCase() === 'false') {
            // boolean FALSE
            obj[key] = false;
        }
        else if (!isNaN(obj[key])) {
            // number
            obj[key] = Number(obj[key]);
        }
        else if ((obj[key].substr(0, 1) === '{' && obj[key].substr(-1) === '}') ||
            (obj[key].substr(0, 1) === '[' && obj[key].substr(-1) === ']')) {
            // JSON
            try {
                obj[key] = JSON.parse(obj[key]);
            }
            catch (e) {
                // continue
            }
        }
    }
    return obj;
}
export function o2a(object, keyName) {
    if (keyName === void 0) { keyName = '$key'; }
    var data = [];
    for (var _i = 0, _a = Object.keys(object || {}); _i < _a.length; _i++) {
        var key = _a[_i];
        if (object[key] instanceof Object) {
            object[key][keyName] = key;
        }
        else {
            var value = object[key];
            object[key] = {};
            object[key][keyName] = key;
            object[key]['value'] = value;
        }
        data.push(object[key]);
    }
    return data;
}
export function a2o(array, keyName) {
    if (keyName === void 0) { keyName = '$key'; }
    var obj = {};
    for (var i = 0, l = (array || []).length; i < l; i++) {
        var item = array[i];
        obj[item[keyName] ||
            item['$key'] ||
            item['slug'] ||
            (item['id'] ? '' + item['id'] : null) ||
            (item['#'] ? '' + item['#'] : null) ||
            ('' + Math.random() * 1E20)] = item;
    }
    return obj;
}
export function uniqueId(length, startWith) {
    if (length === void 0) { length = 12; }
    if (startWith === void 0) { startWith = '-'; }
    var maxLoop = length - 8;
    var ASCII_CHARS = startWith + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
    var lastPushTime = 0;
    var lastRandChars = [];
    var now = new Date().getTime();
    var duplicateTime = (now === lastPushTime);
    lastPushTime = now;
    var timeStampChars = new Array(8);
    var i;
    for (i = 7; i >= 0; i--) {
        timeStampChars[i] = ASCII_CHARS.charAt(now % 64);
        now = Math.floor(now / 64);
    }
    var uid = timeStampChars.join('');
    if (!duplicateTime) {
        for (i = 0; i < maxLoop; i++) {
            lastRandChars[i] = Math.floor(Math.random() * 64);
        }
    }
    else {
        for (i = maxLoop - 1; i >= 0 && lastRandChars[i] === 63; i--) {
            lastRandChars[i] = 0;
        }
        lastRandChars[i]++;
    }
    for (i = 0; i < maxLoop; i++) {
        uid += ASCII_CHARS.charAt(lastRandChars[i]);
    }
    return uid;
}
