package com.braintree.actions.consignment;

import com.braintree.constants.BraintreefulfilmentprocessConstants;
import de.hybris.platform.ordersplitting.model.ConsignmentProcessModel;
import de.hybris.platform.processengine.BusinessProcessService;
import de.hybris.platform.processengine.action.AbstractProceduralAction;
import org.apache.log4j.Logger;


public class BrainTreeSubprocessEndAction extends AbstractProceduralAction<ConsignmentProcessModel> {

    private static final Logger LOG = Logger.getLogger(BrainTreeSubprocessEndAction.class);

    private BusinessProcessService businessProcessService;

    @Override
    public void executeAction(final ConsignmentProcessModel process) {
        LOG.info("Process: " + process.getCode() + " in step " + getClass());

        try {
            // simulate different ending times
            Thread.sleep((long) (Math.random() * 2000));
        } catch (final InterruptedException e) {
            // can't help it
        }

        process.setDone(true);

        save(process);
        LOG.info("Process: " + process.getCode() + " wrote DONE marker");

        businessProcessService.triggerEvent(
                process.getParentProcess().getCode() + "_"
                        + BraintreefulfilmentprocessConstants.CONSIGNMENT_SUBPROCESS_END_EVENT_NAME);
        LOG.info("Process: " + process.getCode() + " fired event "
                + BraintreefulfilmentprocessConstants.CONSIGNMENT_SUBPROCESS_END_EVENT_NAME);
    }

    public void setBusinessProcessService(final BusinessProcessService businessProcessService) {
        this.businessProcessService = businessProcessService;
    }

}
