import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { sendCategoryPageViewEvent } from "@insite/client-framework/OdpEvents/CategoryPageViewEvent";
import { sendSearchNavigationEvent } from "@insite/client-framework/OdpEvents/SearchNavigationEvent";
import { CatalogPage } from "@insite/client-framework/Services/CategoryService";
import { GetProductCollectionApiV2Parameter } from "@insite/client-framework/Services/ProductServiceV2";
import { getCurrentPage } from "@insite/client-framework/Store/Data/Pages/PageSelectors";

type HandlerType = Handler<{
    catalogPage?: CatalogPage;
    lastParameter: GetProductCollectionApiV2Parameter;
}>;

export const SendOdpEvents: HandlerType = async props => {
    let state = props.getState();
    let parameter = state.pages.productList.parameter;

    if (!parameter) {
        return;
    }

    await sendSearchNavigationEvent(
        parameter,
        state.pages.productList.unfilteredApiParameter,
        props.parameter.lastParameter,
        props.getState,
    );

    if (props.parameter.catalogPage) {
        let page = getCurrentPage(state);
        sendCategoryPageViewEvent(page, props.parameter.catalogPage, parameter, state);
    }
};

export const chain = [SendOdpEvents];

const sendOdpEvents = createHandlerChainRunner(chain, "SendOdpEvents");

export default sendOdpEvents;
