import { ApiHandler, createHandlerChainRunner } from "@insite/client-framework/HandlerCreator";
import { getVmiBins, GetVmiBinsApiParameter } from "@insite/client-framework/Services/VmiBinsService";
import { VmiBinCollectionModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandler<GetVmiBinsApiParameter, VmiBinCollectionModel>;

export const PopulateApiParameter: HandlerType = props => {
    props.apiParameter = { ...props.parameter, expand: ["product"] };
};

export const DispatchBeginLoadVmiBins: HandlerType = props => {
    props.dispatch({
        type: "Data/VmiBins/BeginLoadVmiBins",
        parameter: props.parameter,
    });
};

export const DispatchClearVmiBinChecks: HandlerType = props => {
    props.dispatch({
        type: "Pages/VmiBins/ClearVmiItemChecks",
    });
};

export const RequestDataFromApi: HandlerType = async props => {
    try {
        props.apiResult = await getVmiBins(props.apiParameter);
    } catch (error) {
        if ("status" in error && error.status === 404) {
            props.dispatch({
                type: "Data/VmiLocations/FailedToLoadVmiLocation",
                id: props.parameter.vmiLocationId!,
                status: 404,
            });
            return false;
        }
        throw error;
    }
};

export const DispatchCompleteLoadVmiBins: HandlerType = props => {
    props.dispatch({
        type: "Data/VmiBins/CompleteLoadVmiBins",
        collection: props.apiResult,
        parameter: props.parameter,
    });
};

export const chain = [
    PopulateApiParameter,
    DispatchBeginLoadVmiBins,
    DispatchClearVmiBinChecks,
    RequestDataFromApi,
    DispatchCompleteLoadVmiBins,
];

const loadVmiBins = createHandlerChainRunner(chain, "LoadVmiBins");
export default loadVmiBins;
