"use strict";
/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const misc_1 = require("@cocalc/util/misc");
const post_1 = __importDefault(require("lib/api/post"));
const lru_cache_1 = __importDefault(require("lru-cache"));
const react_1 = require("react");
const mounted_1 = __importDefault(require("./mounted"));
// How often to check for new profile.
const DEFAULT_CACHE_S = 10;
// This cache is to avoid flicker when navigating around, since
// we want to show the last known avatar for a given user before
// checking if there is a new one.
const cache = new lru_cache_1.default({ max: 300 });
function useProfile(opts = {}) {
    const { account_id, noCache } = opts;
    const isMounted = (0, mounted_1.default)();
    const [profile, setProfile] = (0, react_1.useState)(noCache ? undefined : cache.get(account_id ?? ""));
    async function getProfile() {
        try {
            const { profile } = await (0, post_1.default)("/accounts/profile", { account_id, noCache }, DEFAULT_CACHE_S);
            if (!isMounted.current)
                return;
            setProfile(profile);
            if (!noCache && (0, misc_1.len)(profile) > 0) {
                // only cache if got actual information.
                cache.set(account_id ?? "", profile);
            }
        }
        catch (err) {
            console.warn("Unable to fetch a profile -- ", err);
        }
    }
    (0, react_1.useEffect)(() => {
        getProfile();
    }, [account_id, noCache]);
    return profile;
}
exports.default = useProfile;
//# sourceMappingURL=profile.js.map