"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoteLiveAppProvider = exports.useManifests = exports.useRemoteLiveAppContext = exports.useRemoteLiveAppManifest = exports.liveAppContext = void 0;
const react_1 = __importStar(require("react"));
const api_1 = __importDefault(require("./api"));
const useIsMounted_1 = __importDefault(require("../../../hooks/useIsMounted"));
const useEnv_1 = __importDefault(require("../../../hooks/useEnv"));
const initialState = {
    isLoading: false,
    value: null,
    error: null,
};
const initialProvider = "production";
const initialParams = {
    branches: ["stable", "soon"],
};
exports.liveAppContext = (0, react_1.createContext)({
    state: initialState,
    provider: initialProvider,
    setProvider: () => { },
    updateManifests: () => Promise.resolve(),
});
function useRemoteLiveAppManifest(appId) {
    const liveAppRegistry = (0, react_1.useContext)(exports.liveAppContext).state;
    if (!liveAppRegistry.value || !appId) {
        return undefined;
    }
    return (liveAppRegistry.value.liveAppFilteredById[appId] || liveAppRegistry.value.liveAppById[appId]);
}
exports.useRemoteLiveAppManifest = useRemoteLiveAppManifest;
function useRemoteLiveAppContext() {
    return (0, react_1.useContext)(exports.liveAppContext);
}
exports.useRemoteLiveAppContext = useRemoteLiveAppContext;
function useManifests(options = {}) {
    const ctx = useRemoteLiveAppContext();
    return (0, react_1.useMemo)(() => {
        const liveAppFiltered = ctx.state?.value?.liveAppFiltered ?? [];
        if (Object.keys(options).length === 0) {
            return liveAppFiltered;
        }
        return liveAppFiltered.filter(manifest => Object.entries(options).some(([key, val]) => {
            switch (key) {
                case "visibility":
                    return val.includes(manifest[key]);
                default:
                    return manifest[key] === val;
            }
        }));
    }, [options, ctx]);
}
exports.useManifests = useManifests;
function RemoteLiveAppProvider({ children, parameters, updateFrequency, }) {
    const isMounted = (0, useIsMounted_1.default)();
    const [state, setState] = (0, react_1.useState)(initialState);
    const [provider, setProvider] = (0, react_1.useState)(initialProvider);
    const { allowExperimentalApps, allowDebugApps, apiVersions, platform, llVersion, lang } = parameters;
    // apiVersion renamed without (s) because param
    const apiVersion = apiVersions ? apiVersions : ["1.0.0", "2.0.0"];
    const envProviderURL = (0, useEnv_1.default)("PLATFORM_MANIFEST_API_URL");
    const providerURL = provider === "production" ? envProviderURL : provider;
    const updateManifests = (0, react_1.useCallback)(async () => {
        setState(currentState => ({
            ...currentState,
            isLoading: true,
            error: null,
        }));
        const branches = [...(initialParams.branches || [])];
        allowExperimentalApps && branches.push("experimental");
        allowDebugApps && branches.push("debug");
        try {
            const allManifests = await api_1.default.fetchLiveAppManifests(providerURL);
            const catalogManifests = await api_1.default.fetchLiveAppManifests(providerURL, {
                apiVersion,
                branches,
                platform,
                private: false,
                llVersion,
                lang: lang ? lang : "en",
            });
            if (!isMounted())
                return;
            setState(() => ({
                isLoading: false,
                value: {
                    liveAppByIndex: allManifests,
                    liveAppFiltered: catalogManifests,
                    liveAppFilteredById: catalogManifests.reduce((acc, liveAppManifest) => {
                        acc[liveAppManifest.id] = liveAppManifest;
                        return acc;
                    }, {}),
                    liveAppById: allManifests.reduce((acc, liveAppManifest) => {
                        acc[liveAppManifest.id] = liveAppManifest;
                        return acc;
                    }, {}),
                },
                error: null,
            }));
        }
        catch (error) {
            if (!isMounted())
                return;
            setState(currentState => ({
                ...currentState,
                isLoading: false,
                error,
            }));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [allowDebugApps, allowExperimentalApps, providerURL, lang, isMounted]);
    const value = (0, react_1.useMemo)(() => ({
        state,
        provider,
        setProvider,
        updateManifests,
    }), [state, provider, setProvider, updateManifests]);
    (0, react_1.useEffect)(() => {
        const interval = setInterval(() => {
            updateManifests();
        }, updateFrequency);
        updateManifests();
        return () => {
            clearInterval(interval);
        };
    }, [updateFrequency, updateManifests]);
    return react_1.default.createElement(exports.liveAppContext.Provider, { value: value }, children);
}
exports.RemoteLiveAppProvider = RemoteLiveAppProvider;
//# sourceMappingURL=index.js.map