/*
 * Copyright 2009 Inspire-Software.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.yes.cart.service.order.impl.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yes.cart.domain.entity.CustomerOrder;
import org.yes.cart.domain.entity.CustomerOrderDelivery;
import org.yes.cart.domain.entity.Shop;
import org.yes.cart.payment.dto.Payment;
import org.yes.cart.service.order.OrderEvent;
import org.yes.cart.service.order.OrderEventHandler;
import org.yes.cart.service.order.OrderException;
import org.yes.cart.service.order.PGDisabledException;
import org.yes.cart.service.payment.PaymentProcessor;
import org.yes.cart.service.payment.PaymentProcessorFactory;

/**
 * User: Igor Azarny iazarny@yahoo.com
 * Date: 09-May-2011
 * Time: 14:12:54
 */
public class ShipmentCompleteOrderEventHandlerImpl extends AbstractEventHandlerImpl implements OrderEventHandler {

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

    private final PaymentProcessorFactory paymentProcessorFactory;

    /**
     * Construct shipment complete transition handler.
     *
     * @param paymentProcessorFactory to get the payment processor
     */
    public ShipmentCompleteOrderEventHandlerImpl(final PaymentProcessorFactory paymentProcessorFactory) {
        this.paymentProcessorFactory = paymentProcessorFactory;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean handle(final OrderEvent orderEvent) throws OrderException {
        synchronized (OrderEventHandler.syncMonitor) {

            final CustomerOrder order = orderEvent.getCustomerOrder();
            final CustomerOrderDelivery thisDelivery = orderEvent.getCustomerOrderDelivery();

            final Shop pgShop = order.getShop().getMaster() != null ? order.getShop().getMaster() : order.getShop();
            final PaymentProcessor paymentProcessor = paymentProcessorFactory.create(order.getPgLabel(), pgShop.getCode());
            if (!paymentProcessor.isPaymentGatewayEnabled()) {
                throw new PGDisabledException("PG " + order.getPgLabel() + " is disabled in " + order.getShop().getCode(), order.getPgLabel());
            }

            if (paymentProcessor.getPaymentGateway().getPaymentGatewayFeatures().isOnlineGateway()) {

                // online capture should be done before shipping in progress
                processDeliveryStates(orderEvent);
                return true;

            } else {

                final String result = paymentProcessor.shipmentComplete(order, thisDelivery.getDeliveryNum(), isForceProcessing(orderEvent), orderEvent.getParams());

                if (Payment.PAYMENT_STATUS_OK.equals(result)) {
                    // payment was ok so continue
                    LOG.info("Funds captured for delivery {}", thisDelivery.getDeliveryNum());

                    processDeliveryStates(orderEvent);
                    return true;


                } else {

                    // must be OK this is offline
                    return false;

                }

            }

        }
    }

    private void processDeliveryStates(final OrderEvent orderEvent) {

        transition(orderEvent, orderEvent.getCustomerOrder(), orderEvent.getCustomerOrderDelivery(),
                CustomerOrderDelivery.DELIVERY_STATUS_SHIPPED);

        for (CustomerOrderDelivery delivery : orderEvent.getCustomerOrder().getDelivery()) {
            if (!CustomerOrderDelivery.DELIVERY_STATUS_SHIPPED.equals(delivery.getDeliveryStatus())) {
                transition(orderEvent, orderEvent.getCustomerOrder(),
                        CustomerOrder.ORDER_STATUS_PARTIALLY_SHIPPED);
                return;
            }
        }
        transition(orderEvent, orderEvent.getCustomerOrder(),
                CustomerOrder.ORDER_STATUS_COMPLETED);

        LOG.info("Order {} completed ", orderEvent.getCustomerOrder().getOrdernum());
    }


    protected boolean isForceProcessing(final OrderEvent orderEvent) {

        final Object forceProcessing = orderEvent.getRuntimeParams().get("forceProcessing");
        return forceProcessing instanceof Boolean && (Boolean) forceProcessing;

    }


}
