<?php

namespace KupShop\KupShopBundle\Util\Compat;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class SymfonyBridge
{
    private static $request;

    public static function handleGlobalRequest()
    {
        $request = static::getCurrentRequest();
        static::handleRequest($request);
    }

    public static function handleRequest(Request $request)
    {
        $kernel = ServiceContainer::getService('kernel');
        if (findModule(\Modules::RESPONSE_CACHE)) {
            // enable for esi:include
            $kernel = new \AppCache($kernel);
        }

        $response = $kernel->handle($request);
        $response->send();
        $kernel->terminate($request, $response);
    }

    public static function handleSubRequest(Request $request)
    {
        $kernel = ServiceContainer::getService('http_kernel');

        $response = $kernel->handle($request, HttpKernelInterface::MAIN_REQUEST);
        $response->send();
    }

    /**
     * @deprecated Use RequestStack->getCurrentRequest()
     */
    public static function getCurrentRequest(): ?Request
    {
        if (findModule(\Modules::COMPONENTS) && !isFunctionalTests()) {
            return ServiceContainer::getService('request_stack')->getCurrentRequest();
        }

        if (!self::$request) {
            self::$request = Request::createFromGlobals();
            Request::setTrustedProxies(
                ['0.0.0.0/0'],
                Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO
            );
        }

        return self::$request;
    }

    /**
     * @param $controller string #Controller
     */
    public static function handleController($controller, $attributes = [])
    {
        $request = static::getCurrentRequest();
        $attributes['_forwarded'] = $request->attributes;
        $attributes['_controller'] = $controller;
        $subRequest = $request->duplicate(null, null, $attributes);

        static::handleSubRequest($subRequest);
    }
}
