<?php

namespace KupShop\OrderingBundle\Admin\Actions;

use KupShop\AdminBundle\Admin\Actions\AbstractAction;
use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\AdminBundle\Admin\Actions\IAction;
use KupShop\AdminBundle\Admin\Actions\OrderActionResult;
use KupShop\AdminBundle\Admin\Actions\OrderActionWrapper;
use KupShop\OrderingBundle\Util\Order\OrderUtil;

class AddDiscountAction extends AbstractAction implements IAction
{
    /** @var OrderUtil */
    private $orderUtil;

    /** @var OrderActionWrapper */
    private $orderActionWrapper;

    /**
     * @required
     */
    public function setOrderActionWrapper(OrderActionWrapper $orderActionWrapper): void
    {
        $this->orderActionWrapper = $orderActionWrapper;
    }

    /**
     * @required
     */
    public function setOrderUtil(OrderUtil $orderUtil): void
    {
        $this->orderUtil = $orderUtil;
    }

    public function getTypes(): array
    {
        return ['orders'];
    }

    public function getName(): string
    {
        return 'Přidat slevu ke všem produktům';
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        $result = $this->orderActionWrapper->wrap(function (\Order $order) use ($config) {
            $roundPrice = !empty($config['roundPrice']);
            $this->orderUtil->addDiscount($order, \Decimal::ensureDecimal($config['items_discount']), $roundPrice);

            return (new OrderActionResult(true, 'Sleva byla nastavena'))->setRecalculate(false);
        });
        writeDownActivity(sprintf(
            getTextString('orders', 'activityMassActionExecuted'),
            $result->getOrder()->order_no,
            'AddDiscountAction',
            !empty($result->getMsg()) ? $result->getMsg() : 'ok'
        ));

        return $result;
    }
}
