<?php
namespace Opentalent\OtOptimizer\Routing;

use Opentalent\OtCore\Website\OtWebsiteRepository;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Routing\SiteRouteResult;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * Hooks into the frontend request and use the ot_websites table to resolve the site configuration
 * (frontend only)
 *
 * @internal
 */
class SiteMatcher extends \TYPO3\CMS\Core\Routing\SiteMatcher
{
    /**
     * Override the default Typo3 \TYPO3\CMS\Core\Routing\SiteMatcher
     *
     * @param ServerRequestInterface $request
     * @return \TYPO3\CMS\Core\Routing\RouteResultInterface
     * @throws \Opentalent\OtCore\Exception\NoSuchWebsiteException
     */
    public function matchRequest(ServerRequestInterface $request): \TYPO3\CMS\Core\Routing\RouteResultInterface
    {
        $devMode = $_SERVER['TYPO3_CONTEXT'] == "Development";

        $otWebsiteRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OtWebsiteRepository::class);

        $site = $otWebsiteRepository->matchUriToWebsite($request->getUri(), $devMode);

        if ($devMode) {
            preg_match("/\w+\/(.*)/", $request->getUri()->getPath(), $m);
            $tail = $m[1] ?? "";
        } else {
            $tail = $request->getUri()->getPath();
        }

        $language = $site->getDefaultLanguage();
        return new SiteRouteResult($request->getUri(), $site, $language, $tail);
    }
}
