<?php

namespace KupShop\AdminBundle\Admin\Actions;

use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\Event\OrderEvent;

class OrderActionWrapper
{
    public function wrap(callable $callback): OrderActionResult
    {
        $orderID = getVal('ID');
        $order = new \Order();
        $order->createFromDB($orderID);
        $contextManager = ServiceContainer::getService(ContextManager::class);
        /** @var $result OrderActionResult */
        $result = $contextManager->activateOrder($order, function () use ($callback, $order) {
            return sqlGetConnection()->transactional(function () use ($callback, $order) {
                /** @var $result OrderActionResult */
                $result = $callback($order);
                $result->setOrder($order);

                if ($result->isRecalculate()) {
                    $order->recalculate();
                }

                sqlQuery("UPDATE orders SET date_updated=NOW() WHERE id='{$order->id}' ");

                $eventDispatcher = ServiceContainer::getService('event_dispatcher');
                $event = new OrderEvent($order);
                $eventDispatcher->dispatch($event, OrderEvent::ORDER_EDITED);

                return $result;
            });
        });

        return $result;
    }
}
