import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { getHomePageUrl } from "@insite/client-framework/Store/Links/LinksSelectors";
import translate from "@insite/client-framework/Translate";
import { LinkProps } from "@insite/mobius/Link";

type HandlerType = Handler<{ links: LinkProps[] | undefined }>;

export const DispatchSetLinks: HandlerType = props => {
    let links = props.parameter.links;
    const homePageUrl = getHomePageUrl(props.getState());

    if (links && links.length > 0 && links.some(o => o.type === "HomePage" || o.type === undefined)) {
        // we need to always direct to the language-specific homepage URL
        const homePageLink = { children: translate("Home_Breadcrumb"), href: homePageUrl };
        const linksWithoutHomePageLink = [...links].splice(1, links.length);
        links = [homePageLink, ...linksWithoutHomePageLink];
    }

    props.dispatch({
        type: "Components/Breadcrumbs/SetLinks",
        links,
    });
};

export const chain = [DispatchSetLinks];

const setBreadcrumbs = createHandlerChainRunner(chain, "SetBreadcrumbs");
export default setBreadcrumbs;
