<?php


namespace AutoAdmin\Bundle\BrickBuilder\Brick;


use AutoAdmin\Bundle\BrickBuilder\Brick\Config\BrickConfiguration;
use AutoAdmin\Bundle\BrickBuilder\Brick\Config\Configurator;
use AutoAdmin\Bundle\BrickBuilder\Brick\Handler\BrickHandlerInterface;
use AutoAdmin\Bundle\BrickBuilder\Exception\InvalidSettingConfigurationException;

class BrickConfigManager
{
    private array $handlers = [];
    private array $settingsConfig = [];

    public function __construct($handlers)
    {
        /** @var BrickHandlerInterface $handler */
        foreach ($handlers as $id => $handler) {
            if (method_exists($handler, 'configure')) {
                $configurator = new Configurator();
                try {
                    $handler->configure($configurator);
                } catch (InvalidSettingConfigurationException $e) {
                    throw new InvalidSettingConfigurationException(
                        $e->getMessage() . sprintf(' (in brick "%s")', $id)
                    );
                }
                $config = $configurator->compile();
                $configuration = new BrickConfiguration($config['options'], $config['settings']);
                $this->settingsConfig[$id] = $configuration;
                $handler->setConfiguration($configuration);
            }

        }
    }

    public function getHandlerConfiguration(string $type): ?BrickConfiguration
    {
        return $this->settingsConfig[$type] ?? null;
    }

    private function add(string $type, BrickHandlerInterface $handler): void
    {
        $this->handlers[$type] = $handler;
    }
}
