<?php


namespace AutoAdmin\Bundle\Admin\Configuration;


use AutoAdmin\Bundle\Admin\DependencyInjection\Configuration\EntityConfiguration;
use Symfony\Component\Config\Definition\Processor;

class ExtraConfigHelper
{
    protected array $baseConfig = [];

    protected array $extraConfigs = [
        'menu' => [],
        'entities' => [],
        'assets' => [],
    ];

    public function __construct(array $baseConfig)
    {
        $this->baseConfig = $baseConfig;
    }

    public function addEntity(string $fqcn, array $config): void
    {
        $entityConfig = new EntityConfiguration();
        $processor = new Processor();
        $processedConfig = $processor->processConfiguration(
            $entityConfig,
            [
                'entities' => [$fqcn => $config],
            ]
        );

        $this->extraConfigs['entities'][$fqcn] = $processedConfig[$fqcn];
    }

    public function addMenuItem($fqcn, $type = 'entity'): void
    {
        $this->extraConfigs['menu'][] = ['class' => $fqcn, 'type' => $type,];
    }

    public function addJs(string $pathOrUrl): void
    {
        $this->extraConfigs['assets']['js'][] = $pathOrUrl;

    }

    public function addCss(string $pathOrUrl): void
    {
        $this->extraConfigs['assets']['css'][] = $pathOrUrl;
    }

    public function getConfig(): array
    {
        foreach ($this->extraConfigs['entities'] as $entityFqcn => $config) {
            if (!isset($this->baseConfig['entities'][$entityFqcn])) {
//            thow new \RuntimeException('Entity "%s" is already defined in configuration.');
                $this->baseConfig['entities'][$entityFqcn] = $config;
            }
        }

        foreach ($this->extraConfigs['menu'] as $config) {
            $this->baseConfig['menu'][] = $config;
        }

        foreach ($this->extraConfigs['assets'] as $type => $urls) {
            foreach ($urls as $url) {
                $this->baseConfig['assets'][$type][] = $url;
            }
        }

        return $this->baseConfig;
    }
}
