<?php


namespace Shop\Modules\AdminProducts;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Form\Simpleform;
use Diamond\Helpers\Form;
use Psr\Log\LoggerAwareInterface;
use Shop\Application\Shopping\MergeProducts\MergeProductsCommand;
use Shop\Application\Shopping\MergeProducts\MergeProductsException;
use spaceonfire\CommandBus\CommandBus;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Class MergerProductsCommand
 * @package Shop\Modules\AdminClients
 */
class MergerProductsCommand implements CommandInterface
{
    protected $tableEngine;
    protected $form;
    protected $commandBus;

    /**
     * MergerProductsCommand constructor.
     * @param DataTableEngine $tableEngine
     * @param Simpleform $form
     */
    public function __construct(DataTableEngine $tableEngine, Simpleform $form, CommandBus $commandBus)
    {
        $this->tableEngine = $tableEngine;
        $this->form = $form;

        $this->commandBus = $commandBus;
    }


    public function process(): void
    {
        $form = $this->form;

        $form->addValidationSuccessEvent([
            $this, 'submit'
        ]);

        $this->tableEngine->addContent($form->render());
    }

    /**
     * @param array $data
     * @param Simpleform $form
     */
    public function submit(array $data, Simpleform $form): void
    {

        $ids = Form::getIdsFromRequest($data);
        $targetId = $data['new_product'];

        try {

            $this->commandBus->handle(new MergeProductsCommand($ids, (int)$targetId));

            Form::addTableNotice(Form::buildSuccessMessage(
                sprintf(
                    'Товары %s успешно объеденены с %s',
                    implode(',',$ids),
                    $targetId
                )
            ));
        }
        catch (MergeProductsException $ex){
            Form::addTableNotice(Form::buildErrorMessage(
                'Не удалось объеденить заказы'
            ));
        }

        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }
}