<?php

namespace AutoAdmin\Bundle\Content\Translation;

use AutoAdmin\Bundle\Content\Context\ContentContext;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Routing\ContentRouter;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Content\Translation\Model\LocaleSwitch;
use Symfony\Component\HttpFoundation\RequestStack;

class LocaleSwitchHelper
{
    public const PUBLIC_PATH_PATTERN = "/bundles/autoadmin/front/images/locale/%s.png";
    public const ADMIN_PATH_PATTERN = "/bundles/autoadmin/back/images/locale/%s.png";

    public function __construct(
        protected SiteContextHelper $contextHelper,
        protected ContentContext $contentContext,
        protected ContentRouter $contentRouter,
        protected EntityTranslator $entityTranslator,
        protected RequestStack $requestStack,
    ) {
    }

    /**
     * @return LocaleSwitch[]
     */
    protected function siteConfigsToLocaleSwitch(): array
    {
        $localeSwitchers = [];

        $isAdmin = $this->requestStack->getCurrentRequest()->get('_admin_locale') !== null;
        $localeImagePattern = $isAdmin ? self::ADMIN_PATH_PATTERN : self::PUBLIC_PATH_PATTERN;
        foreach ($this->contextHelper->getCurrentContextSiteConfigs() as $siteConfig) {
            $localeSwitchers[] = new LocaleSwitch(
                siteConfig: $siteConfig,
                url: null,
                host: $siteConfig->getDomain()->getDomain(),
                image: sprintf($localeImagePattern, $siteConfig->getLocale()),
            );
        }

        return $localeSwitchers;
    }

    protected function prepareDataCurrentContentPass(?object $content = null): array
    {
        return [
            "main_content" => $content,
        ];
    }

    /**
     * @param LocaleSwitch[] $localeSwitches
     * @return LocaleSwitch[]
     */
    protected function localeSwitchCurrentContentPass(array $localeSwitches, array $data = []): array
    {
        if ($dataContent = $data['main_content']) {
            $content = $dataContent;
        } else {
            $content = $this->contentContext->getMainContent();
        }

        foreach ($localeSwitches as $k => $localeSwitch) {
            $locale = $localeSwitch->getLocale();
            $localeCode = $locale->getCode();
            $url = null;
            if ($content) {
                if (
                    $content instanceof TranslatableInterface
                    && $content->getCurrentTranslation()
                    && $content->getCurrentTranslation()->getLocale() !== $locale
                ) {
                    $content = $this->entityTranslator->initializeTranslationInClone($content, $locale);
                }

                $generated = $this->contentRouter->generateSafe(
                    $content,
                    'chain',
                    [
                        '_locale' => $localeCode,
                    ],
                    [
                        'locale' => $localeCode,
                        'host' => $localeSwitch->getHost(),
                    ]
                );

                if ($generated) {
                    $url = $generated;
                }
            }
            $localeSwitch->setUrl($url);
            $localeSwitches[$k] = $localeSwitch;
        }

        return $localeSwitches;
    }

    public function buildCurrentSwitch(?object $content = null): ?LocaleSwitch
    {
        $localeSwitches = array_values(
            array_filter(
                $this->siteConfigsToLocaleSwitch(),
                fn(LocaleSwitch $ls) => $ls->getLocale() === $this->contextHelper->getLocale()
            )
        );
        $localeSwitches = $this->localeSwitchCurrentContentPass(
            $localeSwitches,
            $this->prepareDataCurrentContentPass($content),
        );

        return $localeSwitches[0] ?? null;
    }

    /**
     * @return LocaleSwitch[]
     */
    public function buildAlternateSwitches(?object $content = null): array
    {
        $localeSwitches = array_values(
            array_filter(
                $this->siteConfigsToLocaleSwitch(),
                fn(LocaleSwitch $ls) => $ls->getLocale() !== $this->contextHelper->getLocale()
            )
        );
        $localeSwitches = $this->localeSwitchCurrentContentPass(
            $localeSwitches,
            $this->prepareDataCurrentContentPass($content),
        );

        return $localeSwitches;
    }
}
