<?php


namespace AutoAdmin\Bundle\BrickBuilder\Brick;


use AutoAdmin\Bundle\BrickBuilder\BrickType\BrickNature;
use AutoAdmin\Bundle\BrickBuilder\Model\BrickInterface;
use AutoAdmin\Bundle\BrickBuilder\Model\RenderingBrickInterface;
use Doctrine\Persistence\ManagerRegistry;
use Exception;

class BrickRenderer implements BrickRendererInterface
{
    protected BrickHandlerManagerInterface $manager;
    protected ?string $appEnv = null;
    private ManagerRegistry $doctrine;

    public function __construct(BrickHandlerManagerInterface $manager, ManagerRegistry $doctrine, ?string $appEnv)
    {
        $this->manager = $manager;
        $this->doctrine = $doctrine;
        $this->appEnv = $appEnv;
    }

    public function render(BrickInterface $brick): ?string
    {
        $handler = $this->manager->getHandler($brick);

        if ($handler === null) {
            return null;
        }

        $brick = $this->manager->buildSettings($brick);

        $brick = $handler->preRender($brick, $this->manager);

        if (!$brick instanceof RenderingBrickInterface) {
            throw new Exception(
                'Brick should be instance of '
                . '"AutoAdmin\Bundle\BrickBuilder\Model\RenderingBrickInterface" during render.'
            );
        }

        if ($handler->getConfiguration()->getNature() === BrickNature::NATURE_PROCESS) {
            $handler->process($brick);

            return null;
        }

        return $handler->render($brick, $this);
    }
}
