package com.braintree.actions.consignment;

import de.hybris.platform.commerceservices.model.PickUpDeliveryModeModel;
import de.hybris.platform.core.enums.OrderStatus;
import de.hybris.platform.ordersplitting.model.ConsignmentModel;
import de.hybris.platform.ordersplitting.model.ConsignmentProcessModel;
import de.hybris.platform.processengine.action.AbstractAction;
import de.hybris.platform.warehouse.Process2WarehouseAdapter;
import org.apache.log4j.Logger;

import java.util.HashSet;
import java.util.Set;


public class BrainTreeAllowShipmentAction extends AbstractAction<ConsignmentProcessModel> {

    private static final Logger LOG = Logger.getLogger(BrainTreeAllowShipmentAction.class);
    private Process2WarehouseAdapter process2WarehouseAdapter;

    public enum Transition {
        DELIVERY, PICKUP, CANCEL, ERROR;

        public static Set<String> getStringValues() {
            final Set<String> res = new HashSet<String>();

            for (final Transition transition : Transition.values()) {
                res.add(transition.toString());
            }
            return res;
        }
    }

    @Override
    public String execute(final ConsignmentProcessModel process) {
        final ConsignmentModel consignment = process.getConsignment();
        if (consignment == null) {
            return Transition.ERROR.toString();
        }

        try {
            // Check if the Order is Cancelled
            if (OrderStatus.CANCELLED.equals(consignment.getOrder().getStatus())
                    || OrderStatus.CANCELLING.equals(consignment.getOrder().getStatus())) {
                return Transition.CANCEL.toString();
            } else {
                process2WarehouseAdapter.shipConsignment(process.getConsignment());
                if (consignment.getDeliveryMode() instanceof PickUpDeliveryModeModel) {
                    return Transition.PICKUP.toString();
                } else {
                    return Transition.DELIVERY.toString();
                }
            }
        } catch (final Exception e) {
            LOG.error(e.getMessage(), e);
            return Transition.ERROR.toString();
        }
    }

    public void setProcess2WarehouseAdapter(final Process2WarehouseAdapter process2WarehouseAdapter) {
        this.process2WarehouseAdapter = process2WarehouseAdapter;
    }

    @Override
    public Set<String> getTransitions() {
        return Transition.getStringValues();
    }

}
