import { useAtomValue } from 'jotai';
import { getCodeSample } from '../../services/index.js';
import { globalStoreAtom } from '../../jotai/store.js';
import { operationStore } from '../../jotai/operation.js';
import { environmentAtom, getLangKey, languageAtom, activeMimeNameAtom } from '../../jotai/app.js';
import { useTranslate } from '../../hooks/index.js';
export function useCodeSamples({ payload, isWebhook, definitionSamples, pointer, envVariables, }) {
    const { parser, options: { codeSamples, generatedSamplesMaxDepth }, } = useAtomValue(globalStoreAtom);
    const activeMimeName = useAtomValue(activeMimeNameAtom);
    const operationState = useAtomValue(operationStore(pointer));
    const { languages } = useAtomValue(languageAtom);
    const [environment] = useAtomValue(environmentAtom);
    const translate = useTranslate();
    const orderMap = new Map(languages?.map(({ key, order }) => [key, order]));
    const filteredDefinitionSamples = definitionSamples.filter((item) => orderMap.has(getLangKey(item)));
    const envDefinitionSamples = applyEnvironments(filteredDefinitionSamples, envVariables, environment);
    const definitionExamplesKeys = new Set(envDefinitionSamples.map(getLangKey));
    let generatedSamples = [];
    if (!isWebhook) {
        const generateLanguages = codeSamples.languages?.filter(({ lang, label }) => lang !== 'Payload' && !definitionExamplesKeys.has(getLangKey({ lang, label }))) || [];
        generatedSamples = createCodeSamples(generateLanguages, codeSamples, parser.definition, generatedSamplesMaxDepth, operationState, environment, translate, activeMimeName);
    }
    const allCodeSamples = [...envDefinitionSamples, ...generatedSamples];
    const payloadLabel = languages?.find(({ lang }) => lang === payload?.lang)?.title;
    const payloadLabelKey = payload && getLangKey({ label: payloadLabel, lang: payload.lang });
    if (payload && payloadLabelKey && orderMap.has(payloadLabelKey)) {
        allCodeSamples.push({
            ...payload,
            label: payloadLabel,
            order: orderMap.get(payloadLabelKey),
        });
    }
    // Adding new properties for UI purposes and sort samples
    const samples = allCodeSamples
        .map((sample) => {
        const title = sample.label ?? sample.lang;
        return {
            key: getLangKey(sample),
            title,
            order: typeof orderMap.get(title.toLowerCase()) === 'number'
                ? orderMap.get(title.toLowerCase())
                : 9999,
            ...sample,
        };
    })
        .sort((a, b) => a.order - b.order);
    return { samples };
}
function createCodeSamples(languages, { skipOptionalParameters, withOAuth2Call }, spec, generatedPayloadSamplesMaxDepth, store, environment, translate, activeMimeName) {
    return languages.map(({ lang, label, options }) => {
        return {
            lang,
            label,
            get: (source) => getCodeSample({
                ...source,
                lang,
                options: {
                    ...options,
                    skipOptionalParameters,
                    withOAuth2Call,
                    spec,
                    generatedPayloadSamplesMaxDepth,
                    store,
                    activeMimeName,
                },
                environment,
                translate,
            }),
        };
    });
}
function applyEnvironments(samples, envVariables, currentEnvironment) {
    if (!envVariables || !samples.length)
        return samples;
    const serverUrl = currentEnvironment?.server;
    let envValues = { ...(envVariables.values || {}) };
    if (serverUrl && envVariables.serverValues?.[serverUrl]) {
        envValues = { ...envValues, ...envVariables.serverValues[serverUrl] };
    }
    if (Object.keys(envValues).length === 0)
        return samples;
    return samples.map((sample) => {
        const clonedSample = { ...sample };
        if ('source' in clonedSample && typeof clonedSample.source === 'string') {
            clonedSample.source = clonedSample.source.replace(/\{\{([^}]+)\}\}/g, (match, variableName) => {
                return envValues[variableName] !== undefined ? envValues[variableName] : match; // Keep original if no replacement found
            });
        }
        return clonedSample;
    });
}
//# sourceMappingURL=useCodeSamples.js.map