<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 30.08.2020
 * Time: 23:39
 */

namespace Diamond\Modules\AdminArchiveContents;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Form\Simpleform;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;

class TableRowRestore  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;
        });

        $form = new Simpleform('notice');
        $session = new Session();

        if (!$ids) {
            $session
                ->getFlashBag()
                ->set('table-notice',
                    $form->createMessage('Не выбранны записи для восстановления', Simpleform::MESSAGE_ERROR
                    )
                );
        } 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)
                    );

                $session
                    ->getFlashBag()
                    ->set('table-notice',
                        $form->createMessage(
                            $text, Simpleform::MESSAGE_SUCCESS
                        )
                    );
            }

            if (count($error)) {

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

                $session
                    ->getFlashBag()
                    ->set('table-notice',
                        $form->createMessage(
                            $text, Simpleform::MESSAGE_ERROR
                        )
                    );
            }
        }
        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }

}