class StackImageUpdateActions {

    @Bean(name = "STACK_IMAGE_UPDATE_FAILED_STATE")
    public AbstractStackFailureAction<StackImageUpdateState, StackImageUpdateEvent> handleImageUpdateFailure() {
        return new AbstractStackFailureAction<>() {
            @Inject
            private CloudbreakFlowMessageService flowMessageService;

            @Inject
            private StackUpdater stackUpdater;

            @Inject
            private ComponentConfigProviderService componentConfigProviderService;

            @Inject
            private StackService stackService;

            @Override
            protected void doExecute(StackFailureContext context, StackFailureEvent payload, Map<Object, Object> variables) {
                LOGGER.info("Error during Stack image update flow:", payload.getException());
                if (variables.containsKey(AbstractStackImageUpdateAction.ORIGINAL_IMAGE)) {
                    Image originalImage = (Image) variables.get(AbstractStackImageUpdateAction.ORIGINAL_IMAGE);
                    LOGGER.debug("Reset image to the original");
                    try {
                        Stack stack = stackService.getByIdWithTransaction(context.getStackView().getId());
                        Component component = new Component(ComponentType.IMAGE, ComponentType.IMAGE.name(), new Json(originalImage), stack);
                        componentConfigProviderService.replaceImageComponentWithNew(component);
                        LOGGER.debug("Image restored");
                    } catch (IllegalArgumentException e) {
                        LOGGER.info("Could not parse JSON. Image restore failed");
                    }
                }
                flowMessageService.fireEventAndLog(context.getStackView().getId(), Status.UPDATE_FAILED.name(), STACK_IMAGE_UPDATE_FAILED,
                        payload.getException().getMessage());
                stackUpdater.updateStackStatus(context.getStackView().getId(), DetailedStackStatus.AVAILABLE);
                sendEvent(context, new StackEvent(StackImageUpdateEvent.STACK_IMAGE_UPDATE_FAILE_HANDLED_EVENT.event(),
                        context.getStackView().getId()));
            }
        };
    }

}