"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Gateway_1 = require("../remote-services/Gateway");
const sessions = new Map();
const EXPIRE_TIME = 15 * 60000;
class Session {
    constructor(id) {
        this.id = id;
    }
    setData(data) {
        Object.assign(this, data);
        if (data.gapperToken) {
            this.permissions = undefined;
        }
    }
    async withPermissions() {
        if (this.permissions !== undefined)
            return;
        this.permissions = [];
        const [type, id] = this.id.split('/');
        if (type === 'user') {
            if (!this.gapperToken)
                return;
            const gateway = new Gateway_1.default(this.gapperToken);
            const ret = await gateway.get({
                path: `v1/current-user/permissions`,
                query: { permission$: '{rtsp-proxy.admin}' },
            });
            if (!ret)
                return;
            const permissions = [...ret.permissions].map((it) => `@${it.key}`);
            if (ret.super_admin) {
                permissions.unshift('admin');
            }
            this.permissions.push(...permissions);
        }
        else if (type === 'device') {
            // TODO: 设备的权限
        }
    }
    static set(sessionId, data) {
        const session = Session.get(sessionId);
        session.setData(Object.assign(Object.assign({}, data), { expires: Date.now() + EXPIRE_TIME }));
    }
    static get(sessionId) {
        // 清理过期的session
        const now = Date.now();
        sessions.forEach(({ expires }, key) => {
            if (expires < now) {
                sessions.delete(key);
            }
        });
        let session = sessions.get(sessionId);
        if (!session) {
            session = new Session(sessionId);
            sessions.set(sessionId, session);
        }
        return session;
    }
}
exports.default = Session;
