"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLoggedInLink = getLoggedInLink;
exports.LinksProvider = LinksProvider;
exports.useLinks = useLinks;
exports.useLoadLinks = useLoadLinks;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const utils_1 = require("../utils");
const consts_1 = require("./consts");
const LinksContext = (0, react_1.createContext)(undefined);
/**
 * Adds loggedIn=1 parameter to the URL if 'isLoggedIn' flag is true, which means the user is logged in.
 * If 'isLoggedIn' is falsy, loggedin param will be removed.
 * This is supposed to aid login flow when navigating between Veracity applications.
 */
function getLoggedInLink(link, isLoggedIn) {
    try {
        const url = new URL(link);
        if (isLoggedIn)
            url.searchParams.append('loggedin', '1');
        else
            url.searchParams.delete('loggedin');
        return url.toString();
    }
    catch (_a) {
        return link;
    }
}
function LinksProvider(props) {
    const linksState = (0, react_1.useState)({});
    return (0, jsx_runtime_1.jsx)(LinksContext.Provider, Object.assign({ value: linksState }, props));
}
/** Returns links and setLinks from LinksContext. */
function useLinks() {
    const context = (0, react_1.useContext)(LinksContext);
    if (context === undefined) {
        console.error('useLinks must be used within a LinksContext.');
        return [{}, utils_1.noop];
    }
    return context;
}
/**
 * Retrieves the links from CDN for the given environment and appends them with loggedin=1 parameter
 * if user is logged in. Links will be reloaded when 'env' changes or updated when 'isLoggedIn' changes.
 */
function useLoadLinks(env, isLoggedIn) {
    const [, setLinks] = useLinks();
    // Load links from the CDN for the given environment.
    const loadLinks = (env) => __awaiter(this, void 0, void 0, function* () {
        try {
            const response = yield fetch(`${consts_1.cdnUrls[env]}/common/data/links/base.json`);
            if (!response.ok)
                return;
            const data = yield response.json();
            if ((0, utils_1.isObject)(data))
                setLinks(updateLoggedInParam(data));
        }
        catch (_a) {
            console.error('Failed to retrieve links');
        }
    });
    /**
     * Adds/removes loggedin=1 URL param for each link based on isLoggedIn arg.
     * useCallbackRef is used here to prevent a stale closure in async loadLinks.
     */
    const updateLoggedInParam = (0, utils_1.useCallbackRef)((links) => {
        return Object.keys(links).reduce((loggedInLinks, key) => {
            loggedInLinks[key] = getLoggedInLink(links[key], isLoggedIn);
            return loggedInLinks;
        }, {});
    });
    (0, react_1.useEffect)(() => {
        if (!env)
            return;
        loadLinks(env);
    }, [env]);
    (0, react_1.useEffect)(() => {
        setLinks(updateLoggedInParam);
    }, [isLoggedIn]);
}
//# sourceMappingURL=links.js.map