import { ApiHandlerDiscreteParameter, createHandlerChainRunner } from "@insite/client-framework/HandlerCreator";
import {
    GetWishListLinesApiParameter,
    GetWishListsApiParameter,
} from "@insite/client-framework/Services/WishListService";
import loadWishList from "@insite/client-framework/Store/Data/WishLists/Handlers/LoadWishList";
import { getWishListState } from "@insite/client-framework/Store/Data/WishLists/WishListsSelectors";
import loadWishListLines from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/LoadWishListLines";
import updateLoadWishListLinesParameter from "@insite/client-framework/Store/Pages/MyListDetails/Handlers/UpdateLoadWishListLinesParameter";
import { OrderModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<
    { wishListId: string; keepLinesParameter?: boolean },
    GetWishListsApiParameter,
    OrderModel
>;

export const DispatchSetWishListId: HandlerType = props => {
    props.dispatch({
        type: "Pages/MyListDetails/SetWishListId",
        wishListId: props.parameter.wishListId,
    });
};

export const DispatchLoadWishListIfNeeded: HandlerType = props => {
    const wishListState = getWishListState(props.getState(), props.parameter.wishListId);
    if (
        !wishListState.value ||
        wishListState.value.schedule === undefined ||
        !wishListState.value.sendDayOfMonthPossibleValues ||
        !wishListState.value.sendDayOfWeekPossibleValues ||
        wishListState.value.sendDayOfMonthPossibleValues.length < 1 ||
        wishListState.value.sendDayOfWeekPossibleValues.length < 1 ||
        wishListState.value.wishListTags === null
    ) {
        props.dispatch(
            loadWishList({
                wishListId: props.parameter.wishListId,
                exclude: ["listLines"],
                expand: ["schedule", "sharedUsers", "favorite", "hidden", "tags"],
            }),
        );
    }
};

export const DispatchLoadWishListLinesIfNeeded: HandlerType = props => {
    let param = {
        wishListId: props.parameter.wishListId,
    } as GetWishListLinesApiParameter;

    if (!props.parameter.keepLinesParameter) {
        param = {
            ...param,
            defaultPageSize: props.getState().context.settings.settingsCollection.wishListSettings.productsPerPage,
            query: "",
        };
    }

    props.dispatch(updateLoadWishListLinesParameter(param));

    props.dispatch(loadWishListLines());
};

export const chain = [DispatchSetWishListId, DispatchLoadWishListIfNeeded, DispatchLoadWishListLinesIfNeeded];

const loadWishListIfNeeded = createHandlerChainRunner(chain, "LoadWishListIfNeeded");
export default loadWishListIfNeeded;
