import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { ProductRecommendationModel } from "@insite/client-framework/Services/ProductRecommendationsService";
import prepareTrack from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareTrack";
import { generateGeneralPrepare } from "@insite/client-framework/Store/Components/ProductRecommendations/ProductRecommendationsSelector";
import { getSettingsCollection } from "@insite/client-framework/Store/Context/ContextSelectors";
import { getPageLinkByPageType } from "@insite/client-framework/Store/Links/LinksSelectors";

type HandlerType = Handler<{ url: string }, { recommendation: ProductRecommendationModel }>;

export const PrepareData: HandlerType = props => {
    const {
        getState,
        parameter: { url },
    } = props;

    const state = getState();
    const {
        searchSettings: { searchPath },
    } = getSettingsCollection(state);
    const pages: string[] = [
        "/Catalog",
        "/Product",
        `/${searchPath}`,
        getPageLinkByPageType(state, "CartPage")?.url || "/Cart",
        getPageLinkByPageType(state, "CheckoutReviewAndSubmitPage")?.url || "/CheckoutReviewAndSubmit",
        getPageLinkByPageType(state, "OrderConfirmationPage")?.url || "/OrderConfirmation",
        getPageLinkByPageType(state, "MyListsDetailsPage")?.url || "/MyLists/Details",
    ];

    if (pages.some(o => url.toLowerCase().indexOf(o.toLowerCase()) > -1)) {
        return false;
    }

    props.recommendation = {
        type: "other",
        ...generateGeneralPrepare(getState(), { url }),
    };
};

export const CallPrepareTrack: HandlerType = ({ dispatch, recommendation }) => {
    dispatch(prepareTrack({ prepareTrackData: recommendation }));
};

export const chain = [PrepareData, CallPrepareTrack];

const prepareOther = createHandlerChainRunner(chain, "PrepareOther");
export default prepareOther;
