<?php

namespace WordpressModels\DependencyInjection\RestRouteAttributes;

use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\Extension;
use WordpressModels\Rest\Attribute\RestRoute;
use WordpressModels\Rest\RestControllerInterface;

class RestRouteAttributesExtension extends Extension
{

    public function getNamespace()
    {
        return 'https://code.rtmbusiness.nl/schema/dic/' . $this->getAlias();
    }

    public function getAlias(): string
    {
        return 'wp_rest_route_attributes';
    }

    public function load(array $configs, ContainerBuilder $container)
    {
        $container->registerAttributeForAutoconfiguration(RestRoute::class, self::tagRestService(...));
    }

    public static function tagRestService(ChildDefinition                    $definition,
                                          RestRoute                          $route,
                                          \ReflectionMethod|\ReflectionClass $reflector): ChildDefinition
    {
        // set lazy
        $definition->setLazy(true);

        if ($reflector instanceof \ReflectionMethod) {
            $class = $reflector->getDeclaringClass();
            $definition->addTag('wp_rest_controller', [
                '$scope' => $class->getName(),
                '$method' => $reflector->getName(),
                '$route' => $route->route,
                '$methods' => $route->methods,
                '$permission' => $route->permission,
                '$arguments' => $route->arguments,
                '$override' => $route->override,
                '$public' => $route->public,
                '$namespace' => $route->namespace
            ]);
        } else {
            $definition->addTag('wp_rest_controller_scope', [
                '$name' => $reflector->getName(),
                '$route' => $route->route,
                '$override' => $route->override,
                '$public' => $route->public,
                '$namespace' => $route->namespace,
                '$permission' => $route->permission
            ]);
        }
        return $definition;
    }

}