<?php


namespace AutoAdmin\Bundle\Content\Controller;

use InvalidArgumentException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

class IndexController extends AbstractContentController
{
    public function internationalizationRedirect(
        Request $request,
        string  $path,
        bool    $permanent = true,
        string  $scheme = null,
        string  $port = null
    ): RedirectResponse
    {
        if (strlen($path) <= 1) {
            throw new InvalidArgumentException('No path given for "index_redirection" route.');
        }

        $statusCode = $permanent ? 301 : 302;

        // redirect if the path is a full URL
        if (parse_url($path, PHP_URL_SCHEME)) {
            return new RedirectResponse($path, $statusCode);
        }

        if (null === $scheme) {
            $scheme = $request->getScheme();
        }

        $qs = $request->getQueryString();
        if ($qs) {
            if (false === strpos($path, '?')) {
                $qs = '?' . $qs;
            } else {
                $qs = '&' . $qs;
            }
        }

        if ($scheme === null) {
            $scheme = 'https';
        }

        if ($port === null || $port === 80 || $port === 443) {
            $port = '';
        } else {
            $port = ':' . $port;
        }

        $url = $scheme . '://' . $request->getHost() . $port . $request->getBaseUrl() . $path . $qs;


        return new RedirectResponse($url, $statusCode);
    }
}
