"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Config_1 = require("../lib/Config");
const REST_1 = require("./REST");
let currentAppToken;
const tokenMap = new Map();
class Gateway extends REST_1.default {
    constructor(token) {
        super(`${Config_1.default.gapper.baseUrl}/api`);
        if (token)
            this.token = token;
    }
    get additionalHeaders() {
        return this.token ? { 'X-Gapper-OAuth-Token': this.token } : {};
    }
    get additionalQueries() {
        return {};
    }
    get accessToken() {
        return this.token;
    }
    setAccessToken(token) {
        this.token = token;
    }
    async getOwner() {
        if (!this.token)
            return;
        // 清理过期的token
        const now = Date.now();
        tokenMap.forEach(({ expires }, key) => {
            if (expires < now) {
                tokenMap.delete(key);
            }
        });
        if (tokenMap.has(this.token)) {
            return tokenMap.get(this.token).owner;
        }
        const owner = await this.get('v1/auth/owner');
        if (owner) {
            tokenMap.set(this.token, { owner, expires: now + 3600000 }); // 1h 内认证有效
        }
        else {
            // 设置一个不再重试的缓冲期
            tokenMap.set(this.token, { expires: now + 60000 });
        }
        return owner;
    }
    static async currentAppToken() {
        const clientId = Config_1.default.gapper.clientId;
        const clientSecret = Config_1.default.gapper.clientSecret;
        const gateway = new Gateway();
        if (currentAppToken && currentAppToken.expires < Date.now()) {
            if (currentAppToken.refresh_token) {
                currentAppToken = Object.assign(Object.assign({}, currentAppToken), (await gateway.post('v1/auth/refresh-token', {
                    client_id: clientId,
                    client_secret: clientSecret,
                    refresh_token: currentAppToken.refresh_token,
                })));
            }
            else {
                currentAppToken = undefined;
            }
        }
        if (!currentAppToken) {
            currentAppToken = await gateway.post('v1/auth/app-token', {
                client_id: clientId,
                client_secret: clientSecret,
            });
        }
        return currentAppToken === null || currentAppToken === void 0 ? void 0 : currentAppToken.access_token;
    }
}
exports.default = Gateway;
