import { OdpEvent } from "@insite/client-framework/OdpEvents/OdpEvent";
import { sendPageViewEvent } from "@insite/client-framework/OdpEvents/PageViewEvent";
import { CatalogPage } from "@insite/client-framework/Services/CategoryService";
import { GetProductCollectionApiV2Parameter } from "@insite/client-framework/Services/ProductServiceV2";
import ApplicationState from "@insite/client-framework/Store/ApplicationState";
import { getProductsDataView } from "@insite/client-framework/Store/Data/Products/ProductsSelectors";
import { ProductModel } from "@insite/client-framework/Types/ApiModels";
import PageProps from "@insite/client-framework/Types/PageProps";

export const sendCategoryPageViewEvent = (
    page: PageProps,
    catalogPage: CatalogPage,
    apiParameter: GetProductCollectionApiV2Parameter | undefined,
    state: ApplicationState,
    customize?: (odpEvent: OdpEvent) => void,
) => {
    sendPageViewEvent(page, state, odpEvent => {
        odpEvent.properties["action"] = "category";

        setCategory(odpEvent, catalogPage);

        let products = getProductsDataView(state, apiParameter)?.value;
        if (products) {
            odpEvent.properties["search_product_details"] = JSON.stringify(
                products.map(o => ({
                    product_id: o.id,
                })),
            );
        }

        customize?.(odpEvent);
    });
};

export const setCategory = (odpEvent: OdpEvent, catalogPage: CatalogPage) => {
    if (catalogPage.breadCrumbs) {
        let category = "";
        for (let x = 1; x < catalogPage.breadCrumbs.length; x++) {
            category += `${catalogPage.breadCrumbs![x].text} > `;
        }

        if (category.length > 3) {
            category = category.substring(0, category.length - 3);
        }

        odpEvent.properties["category"] = category;
    }
};
