<?php

namespace KupShop\KupShopBundle\Util\Locale;

use Gettext\Translator;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Symfony\Bridge\Monolog\Logger;

class WarningGettextTranslator extends Translator
{
    public function getPluralTranslateData($domain, $context, $original): array
    {
        if ($domain === null) {
            $domain = $this->domain;
        }

        return [
            array_map(fn ($x) => '"'.$this->escapePluralText($x).'"', $this->getTranslation($domain, $context, $original)),
            $this->plurals[$domain]['code'] ?? null,
        ];
    }

    protected function getTranslation($domain, $context, $original)
    {
        $result = parent::getTranslation($domain, $context, $original);

        if ($result === false || $result[0] === '') {
            // Nereportovat chyby v defaultnim jazyku
            $languageContext = ServiceContainer::getService(LanguageContext::class);

            // Templaty jsou vzdy v cestine, proto reportujeme jen jazyky mimo cestinu
            if ($languageContext->getActiveId() == 'cs') {
                return [$original];
            }

            // Log missing string to Kibana if in production
            if (!isDevelopment()) {
                /** @var Logger $logger */
                $logger = ServiceContainer::getService('logger');
                $logger->warning("Missing template translation: \"{$original}\", with context: \"{$context}\" in domain: \"{$domain}\"", [
                    'original' => $original,
                    'context' => $context,
                    'language' => $languageContext->getActiveId(),
                ]);

                return [$original];
            }

            return ["!{$original}!"];
        }

        return $result;
    }

    private function escapePluralText(string $text): string
    {
        return str_replace('"', '\"', $text);
    }
}
