<?php


namespace AutoAdmin\Bundle\BrickBuilder\Twig\Extension;

use AutoAdmin\Bundle\BrickBuilder\Brick\BrickAdminHelper;
use AutoAdmin\Bundle\BrickBuilder\Brick\BrickHandlerManagerInterface;
use AutoAdmin\Bundle\BrickBuilder\Brick\BrickRendererInterface;
use AutoAdmin\Bundle\BrickBuilder\Brick\Handler\BrickHandlerInterface;
use AutoAdmin\Bundle\BrickBuilder\Model\BrickInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class BrickExtension extends AbstractExtension
{
    private BrickRendererInterface $renderer;
    private BrickHandlerManagerInterface $handlerManager;
    private BrickAdminHelper $adminHelper;

    public function __construct(
        BrickRendererInterface       $renderer,
        BrickHandlerManagerInterface $handlerManager,
        BrickAdminHelper             $adminHelper
    )
    {
        $this->renderer = $renderer;
        $this->handlerManager = $handlerManager;
        $this->adminHelper = $adminHelper;
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('aa_brick_render', [$this, 'brickRender'], ['is_safe' => ['html']]),
            new TwigFunction('aa_brick_is_container', [$this, 'isContainerBrick']),
            new TwigFunction('aa_brick_get_allowed_children', [$this, 'getAllowedChildren']),
            new TwigFunction('aa_brick_get_categories', [$this, 'getBrickCategories']),
            new TwigFunction('aa_brick_get_preview', [$this, 'getAdminPreview'], ['is_safe' => ['html']]),
            new TwigFunction('aa_brick_get_handler', [$this, 'getBrickHandler']),
            new TwigFunction('aa_brick_has_form', [$this, 'hasAdminForm']),
        ];
    }

    public function brickRender(BrickInterface $brick, array $settings = []): ?string
    {
        return $this->renderer->render($brick);
    }

    public function isContainerBrick($brick): bool
    {
        return $this->adminHelper->isContainerBrick($brick);
    }

    public function getAdminPreview(BrickInterface $brick): ?string
    {
        return $this->adminHelper->getAdminPreview($brick);
    }

    public function getBrickHandler(BrickInterface $brick): ?BrickHandlerInterface
    {
        return $this->handlerManager->getHandler($brick);
    }

    public function hasAdminForm($brick): bool
    {
        return $this->adminHelper->hasAdminForm($brick);
    }

    public function getAllowedChildren(BrickInterface $brick)
    {
        return $this->adminHelper->getAllowedChildren($brick);
    }

    public function getBrickCategories(BrickInterface $brick)
    {
        $this->adminHelper->getBrickCategories();
    }
}
