<?php

namespace AutoAdmin\Bundle\Content\Routing;

use AutoAdmin\Bundle\Content\Configuration\ConfigManager;
use RuntimeException;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ContentRouteLoader extends Loader
{
    private ConfigManager $config;
    private bool $isLoaded = false;

    public function __construct(ConfigManager $config, string $env = null)
    {
        parent::__construct($env);
        $this->config = $config;
    }

    /**
     * @inheritDoc
     */
    public function load($resource, string $type = null): RouteCollection
    {
        if (true === $this->isLoaded) {
            throw new RuntimeException('Do not add the "auto_admin_content" loader twice');
        }

        $routes = new RouteCollection();
        foreach ($this->config->getRoutes() as $routeName => $route) {
            $route = $this->buildRouteFromConfig($routeName, $route);
            $routes->add($routeName, $route);
        }

        $this->isLoaded = true;

        return $routes;
    }

    public function buildRouteFromConfig(string $routeName, array $routeConfig): Route
    {
        $path = $routeConfig['path'];
        $defaults = $routeConfig['defaults'] ?? [];
        if (!empty($routeConfig['controller']) && $controller = $routeConfig['controller']) {
            if (stripos($controller, '::') === false) {
                $action = preg_replace('#[^a-z_]+#', '', substr($routeName, stripos($routeName, '_') + 1));
                $defaults['_controller'] = $controller . '::' . $action;
            } else {
                $defaults['_controller'] = $controller;
            }
            unset($defaults['controller']);
        }

        $requirements = $routeConfig['requirements'] ?? [];
        $options = $routeConfig['options'] ?? [];
        $host = $routeConfig['host'] ?? '';
        $schemes = $routeConfig['schemes'] ?? [];
        $methods = $routeConfig['methods'] ?? [];
        $condition = $routeConfig['condition'] ?? '';

        return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
    }

    /**
     * @inheritDoc
     */
    public function supports($resource, string $type = null): bool
    {
        return $type === 'auto_admin_content';
    }
}
