<?php


namespace Diamond\Modules\AdminArchivePages;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Helpers\Form;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\RedirectResponse;

class PageRestoreCommand implements CommandInterface, LoggerAwareInterface
{
    use LoggerAwareTrait;

    protected $tableEngine;

    public function __construct(DataTableEngine $tableEngine)
    {
        $this->tableEngine = $tableEngine;
        $this->logger = new NullLogger();
    }

    /**
     *
     */
    public function process(): void
    {
        $engine = $this->tableEngine;

        $postData = $engine->getRequest()->getParsedBody();

        $ids = isset($postData['ids']) ? explode(',', trim($postData['ids'], ',')) : null;
        $ids = array_filter($ids, function ($v) {
            return $v > 0;
        });


        if (!$ids) {
            Form::addTableNotice(
                Form::buildErrorMessage('Не выбранны записи для восстановления')
            );
        } else {

            $success = $error = [];

            foreach ($ids as $id) {
                try {
                    if (!$entity = $engine->getRepo()->findById($id)) {
                        throw new \RuntimeException('entity not found by id ' . $id);
                    }
                    $engine->getRepo()->restore($entity);
                    $success [] = $id;
                } catch (\RuntimeException $ex) {
                    $error [] = $id;
                    $this->logger->error($ex->getMessage());
                }
            }

            if (count($success)) {

                $text = count($ids) === 1 ?
                    sprintf(
                        'Выбранная запись %s успешно восстановлена!',
                        implode(',', $success)
                    ) :
                    sprintf(
                        'Выбранные записи %s успешно восстановлены!',
                        implode(',', $success)
                    );

                Form::addTableNotice(
                    Form::buildSuccessMessage($text)
                );
            }

            if (count($error)) {

                $text = count($ids) === 1 ?
                    sprintf(
                        'Запись %s не удалось восстановить',
                        implode(',', $error)
                    ) :
                    sprintf(
                        'Следующие записи %s не получилось удалить',
                        implode(',', $error)
                    );

                Form::addTableNotice(
                    Form::buildErrorMessage($text)
                );

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

}