<?php

declare(strict_types=1);

namespace KupShop\AdminBundle\Admin\Actions;

use KupShop\AdminBundle\Util\ActivityLog;
use KupShop\AdminBundle\Util\AdminClassLocator;
use KupShop\KupShopBundle\Exception\RedirectException;
use Symfony\Contracts\Service\Attribute\Required;

class DeleteAction extends AbstractAction implements IAction
{
    #[Required]
    public AdminClassLocator $adminClassLocator;

    public function getTypes(): array
    {
        return ['productsOfSuppliers', 'users', 'languages', 'rewrite', 'OrderDiscounts'];
    }

    public function getName(): string
    {
        return translate('windowDelete', 'button');
    }

    public function getPriority(): int
    {
        return self::PRIORITY_DELETE;
    }

    public function getIcon(): string
    {
        return 'glyphicon glyphicon-trash';
    }

    public function getColorText()
    {
        return self::COLOR_DANGER;
    }

    public function showInMassEdit()
    {
        return true;
    }

    public function getVars(): array
    {
        $vars = parent::getVars();

        $type = str_replace('.php', '', getVal('s'));
        $confirmDelete = translate('confirmDelete', $type, true);
        if (!$confirmDelete) {
            $confirmDelete = translate('confirmDelete', 'base');
        }
        $vars['confirmDelete'] = $confirmDelete;

        return $vars;
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        try {
            $result = sqlGetConnection()->transactional(function () use ($type) {
                try {
                    if (!isset($this->window)) {
                        // there is no window in case of mass edit, try to create
                        $fullClassPath = $this->adminClassLocator->getClassPath($type.'.php');
                        $window = $this->adminClassLocator->createClass($fullClassPath, $type);
                        $window->setType($type);
                        $this->setWindow($window);
                    }
                    $this->getWindow()->setID($this->getId());
                    $this->getWindow()->handleDelete();
                } catch (RedirectException $e) {
                    // RedirectException is thrown after successful deletion
                    return (new ActionResult(true))->setRedirect(['acn' => 'erased']);
                }
            });
        } catch (\Exception $exception) {
            $activityMessage = sprintf('%s: objekt s ID "%s": Akce [%s] se nezdařila.',
                $this->getWindow()->translateType(), $this->getId(), $this->getName());
            addActivityLog(ActivityLog::SEVERITY_ERROR, ActivityLog::TYPE_CHANGE, $activityMessage,
                ['exception' => $exception->getMessage()]);
            $result = new ActionResult(false);
        }

        return $result;
    }
}
