<?php

namespace AutoAdmin\Bundle\Admin\Factory;

use AutoAdmin\Bundle\Admin\Builder\LayoutBuilder;
use AutoAdmin\Bundle\Admin\Builder\TableBuilder;
use AutoAdmin\Bundle\Admin\Configuration\ConfigManager;
use AutoAdmin\Bundle\Admin\Helper\AccessHelper;
use AutoAdmin\Bundle\Admin\Helper\EntityHelper;
use AutoAdmin\Bundle\Admin\Helper\StringifierHelper;
use AutoAdmin\Bundle\Admin\Router\AdminRouter;
use AutoAdmin\Bundle\Admin\Search\EntitySearchHelper;
use Doctrine\ORM\EntityManagerInterface;
use Exception;

class BuilderFactory
{
    private EntityManagerInterface $entityManager;
    private ConfigManager $configManager;
    private EntityHelper $entityHelper;
    private AdminRouter $adminRouter;
    private AccessHelper $accessHelper;
    private StringifierHelper $stringifierHelper;
    private EntitySearchHelper $entitySearchHelper;

    public function __construct(
        EntityManagerInterface $entityManager,
        ConfigManager          $configManager,
        EntityHelper           $entityHelper,
        AdminRouter            $adminRouter,
        AccessHelper           $accessHelper,
        StringifierHelper      $stringifierHelper,
        EntitySearchHelper     $entitySearchHelper
    )
    {
        $this->entityManager = $entityManager;
        $this->configManager = $configManager;
        $this->entityHelper = $entityHelper;
        $this->adminRouter = $adminRouter;
        $this->accessHelper = $accessHelper;
        $this->stringifierHelper = $stringifierHelper;
        $this->entitySearchHelper = $entitySearchHelper;
    }

    public function getTableBuilder(): TableBuilder
    {
        return $this->get('table');
    }

    /**
     * @throws Exception
     */
    public function get(string $builderName)
    {
        $className = 'AutoAdmin\\Bundle\Admin\\Builder\\' . ucfirst($builderName) . 'Builder';

        if (!class_exists($className)) {
            throw new Exception($className . " doesn't exist");
        }

        return new $className(
            $this->entityManager,
            $this->configManager,
            $this->entityHelper,
            $this->adminRouter,
            $this->accessHelper,
            $this->stringifierHelper,
            $this->entitySearchHelper,
        );
    }

    public function getLayoutBuilder(): LayoutBuilder
    {
        return $this->get('layout');
    }
}
