import { useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { get, getIn } from 'lodash';
import { hooks, unstable } from '@broadleaf/admin-components';
const { useTracking, useTranslateMode } = hooks;
const { ContextRequest } = unstable;
const { ContextParameters } = ContextRequest;
export const useContextParams = (metadata, state) => {
// if the metadata marks this as trackable, this will return an object with
// the tracking info needed for the context request header using the catalog,
// tenant, and sandbox contexts
const tracking = useTracking(metadata);
// on main entity form, the ID is in the URL unless this is a create, in that
// case there is no ID yet
const { id } = useParams();
// this is important for sandbox entities for grouping together their changes
const containerName = getIn(metadata, `attributes.changeContainer`);
// let's us get the translate mode context and actions to see if we're in it
const translateMode = useTranslateMode();
return useMemo(() => {
let contextParams = {};
if (id) {
contextParams.id = id;
}
if (isSandboxDiscriminated(metadata) && containerName) {
contextParams[ContextParameters.CHANGE_CONTAINER] = buildChangeContainer(
containerName,
id
);
}
if (tracking) {
contextParams[ContextParameters.TRACKING] = tracking;
}
if (metadata.translatable && translateMode.isActive) {
contextParams[ContextParameters.LOCALE] = translateMode.locale;
}
// this is important for compile the template paths such as
// `/products/${parent.id}/variants/${id}`
if (state && state.data) {
contextParams.parent = state.data;
if (state.data.contextState) {
contextParams[ContextParameters.CONTEXT_STATE] =
state.data.contextState;
}
}
return contextParams;
}, [state, tracking]);
}
const isSandboxDiscriminated = metadata => {
return !!get(metadata, 'attributes.sandboxDiscriminated', false);
}
const buildChangeContainer = (containerName, containerId, subContainerName) => {
const changeContainer = { name: containerName };
if (!!containerId) {
changeContainer.id = containerId;
}
if (!!subContainerName) {
changeContainer.subContainerName = subContainerName;
}
return changeContainer;
}