import { getUrl } from "@insite/client-framework/ServerSideRendering";
import { getTheme } from "@insite/client-framework/Services/ContentService";
import {
    getSiteMessages,
    getTranslationDictionary,
    readAsyncWidgetFieldDefinitions,
} from "@insite/server-framework/InternalService";
import NodeCache from "node-cache";

let nodeCache = new NodeCache();

const getOrAdd = async <T>(key: string, get: () => Promise<T>) => {
    let result = nodeCache.get<T>(key);
    if (result === undefined) {
        result = await get();
        nodeCache.set(key, result, 60);
    }

    return result;
};

export const getCachedTheme = () => {
    return getOrAdd(`Theme_${getUrl()}`, getTheme);
};

export const getCachedSiteMessages = (languageCode: string) => {
    return getOrAdd(`SiteMessages_${languageCode}`, () => getSiteMessages(languageCode));
};

export const getCachedTranslationDictionary = (languageCode: string) => {
    return getOrAdd(`TranslationDictionary_${languageCode}`, () => getTranslationDictionary(languageCode));
};

export const getCachedAsyncWidgetFieldDefinitions = () => {
    return getOrAdd(`AsyncWidgetFieldDefinitions`, () => readAsyncWidgetFieldDefinitions());
};
