<?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)
    {
        $this->settingsConfig = self::configureHandlers($handlers);
    }

    /**
     * We need to be able to configure the handlers during tests,
     * so we made this logic static to comply with both contexts (app and tests)
     *
     * @param array $handlers
     * @return array
     * @throws InvalidSettingConfigurationException
     */
    public static function configureHandlers(array $handlers): array
    {
        $settingsConfigs = [];

        /** @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']);
                $settingsConfigs[$id] = $configuration;
                $handler->setConfiguration($configuration);
            }

        }

        return $settingsConfigs;
    }

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

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