<?php

namespace KupShop\LocalePrefixBundle\Util;

use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Contexts;
use Symfony\Component\HttpFoundation\Request;

class LocalePrefixUtil
{
    private ?LanguageContext $languageContext;

    public function getLanguageFromPath(string $path): ?string
    {
        $langRaw = substr($path, 1, 3);
        $lang = trim($langRaw, '/');
        $languages = $this->getLanguageContext()->getSupported();

        return (str_ends_with($langRaw, '/') && isset($languages[$lang])) ? $lang : null;
    }

    public function getPathWithoutPrefix(string $path): string
    {
        return $this->getLanguageFromPath($path) ? mb_substr($path, 3) : $path;
    }

    public function setRequestAttribute(Request $request)
    {
        if ($this->getLanguageFromPath($request->getPathInfo())) {
            $request->attributes->set('uri-without-language-prefix', mb_substr($request->getRequestUri(), 3));
        }
    }

    public function setLanguageFromLocalePrefix(string $path)
    {
        $languageContext = $this->getLanguageContext();
        $languageContext->activate($this->getLanguageFromPath($path) ?? $languageContext->getDefaultId());
    }

    public function setLanguageContext(LanguageContext $languageContext): self
    {
        $this->languageContext = $languageContext;

        return $this;
    }

    private function getLanguageContext(): LanguageContext
    {
        return $this->languageContext ?? Contexts::get(LanguageContext::class);
    }
}
