<?php

namespace External\VarioBundle\Resources\script;

use External\VarioBundle\Synchronizers\OrderSynchronizer;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class VarioSendOrderScript extends Script
{
    protected static $name = '[Vario] Send Order to Vario';
    protected static $defaultParameters = [
        'format' => 'json',
        'dryRun' => true,
        'orderID' => null,
    ];

    protected function run(array $arguments)
    {
        $contextManager = ServiceContainer::getService(ContextManager::class);
        $orderSynchronizer = ServiceContainer::getService(OrderSynchronizer::class);

        $this->log('Running '.($arguments['dryRun'] ? 'in DRY RUN' : 'in PRODUCTION mode').'... ');

        $order = new \Order();
        $order->createFromDB($arguments['orderID']);

        $contextManager->activateOrder($order, function () use ($arguments, $order, $orderSynchronizer) {
            $order->fetchItems();

            if ($arguments['dryRun']) {
                $data = $orderSynchronizer->createDocumentObject($order);
                $this->log($arguments['format'] === 'json' ? json_encode($data, JSON_PRETTY_PRINT) : print_r($data, true));
            } else {
                $result = $orderSynchronizer->syncOrder($order);
                $this->log($result ? 'OK' : 'ERROR');
            }
        });

        $this->log('Done');
    }
}

return VarioSendOrderScript::class;
