<?php


namespace AutoAdmin\Bundle\BrickBuilder\Brick;


use AutoAdmin\Bundle\BrickBuilder\Brick\Handler\BrickAdminPreviewInterface;
use AutoAdmin\Bundle\BrickBuilder\BrickType\BrickCategory;
use AutoAdmin\Bundle\BrickBuilder\BrickType\BrickNature;
use AutoAdmin\Bundle\BrickBuilder\Model\BrickInterface;
use AutoAdmin\Bundle\Content\Service\ObfuscatorService;
use Symfony\Contracts\Translation\TranslatorInterface;

class BrickAdminHelper
{
    private BrickHandlerManagerInterface $handlerManager;
    private TranslatorInterface $translator;

    public function __construct(BrickHandlerManagerInterface $handlerManager, TranslatorInterface $translator)
    {
        $this->handlerManager = $handlerManager;
        $this->translator = $translator;
    }

    public function getAdminPreview(BrickInterface $brick): ?string
    {
        $handler = $this->handlerManager->getHandler($brick);
        $brick = $this->handlerManager->buildSettings($brick);

        if ($handler instanceof BrickAdminPreviewInterface) {
            $adminPreview = $handler->getAdminPreview($brick);

            return ObfuscatorService::obfuscate($adminPreview);
        }

        if ($handler->getConfiguration()->getNature() === BrickNature::NATURE_CONTENT) {
            $label = null;
            if (in_array(
                $brick->getSetting('_category'),
                [
                    BrickCategory::CATEGORY_DYNAMIC,
                    BrickCategory::CATEGORY_PROCESS,
                    BrickCategory::CATEGORY_COMPLEX,
                ]
            )) {
                $label = $this->translator->trans('preview.' . $brick->getSetting('_category'), [], 'aa_admin');
                $label = sprintf('<em>[%s]</em>', $label);
            }

            return $label;
        }

        return null;
    }

    public function getAllowedChildren(BrickInterface $brick)
    {
        $type = $brick->getType();
        $typeConstraints = $this->handlerManager->getHierarchyConstraints();
        return $typeConstraints[$type];
    }

    public function getBrickCategories(): array
    {
        return $this->handlerManager->getBrickCategories();
    }

    public function hasAdminForm(BrickInterface $brick): bool
    {
        $handler = $this->handlerManager->getHandler($brick);

        return $handler->getConfiguration()->hasForm();
    }

    public function isContainerBrick(BrickInterface $brick): bool
    {
        return $this->getBrickNature($brick) === BrickNature::NATURE_LAYOUT;
    }

    public function getBrickNature(BrickInterface $brick)
    {
        $handler = $this->handlerManager->getHandler($brick);

        return $handler->getConfiguration()->getNature();
    }

    public function getBrickTypes(): array
    {
        return $this->handlerManager->getBrickTypes();
    }
}
