<?php declare(strict_types=1);
namespace Newland\Toubiz\Poi\Neos\Service;

/*
 * This file is part of the "toubiz-poi-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\I18n\Locale;
use Neos\Flow\I18n\Service;
use Neos\Flow\I18n\Translator;

/**
 * @Flow\Scope("singleton")
 */
class AttributeTopicService
{
    /**
     * @var Translator
     * @Flow\Inject
     */
    protected $translator;

    /**
     * @var Service
     * @Flow\Inject
     */
    protected $localizationService;

    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Poi.Neos", path="attributes.i18n")
     */
    protected $translationConfiguration;

    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Poi.Neos", path="attributes")
     */
    protected $attributeConfiguration;

    /**
     * @param string $name
     * @param string|null $value
     * @return string
     */
    public function titleForAttribute(string $name, $value = null): string
    {
        $label = 'attribute.' . $name;
        if (\is_string($value)) {
            $label .= '.' . $value;
        }

        $configurations = $this->translationConfiguration;
        $configurations[] = [ 'package' => 'Newland.Toubiz.Poi.Neos' ];

        foreach ($configurations as $config) {
            $title = $this->getTranslationWithLanguageFallback($config, $label);
            if ($title) {
                return $title;
            }
        }

        return $label;
    }

    public function getConfiguredIdentifiers($mainType = 'default'): array
    {
        return $this->attributeConfiguration['articleTypes'][$mainType] ?? [];
    }

    public function getTranslationWithLanguageFallback(
        array $config,
        string $label,
        Locale $locale = null,
        array $parsedLanguages = []
    ): string {
        $locale = $locale ?? $this->localizationService->getConfiguration()->getCurrentLocale();
        $source = $config['source'] ?? 'Models/Topic';
        $package = $config['package'];
        $translation = $this->translator->translateById($label, [], null, $locale, $source, $package);

        if ($translation) {
            return $translation;
        }

        $localeChain = $this->localizationService->getLocaleChain($locale);
        $locale = next($localeChain);
        if ($locale !== false && in_array($locale->getLanguage(), $parsedLanguages, true) === false) {
            $parsedLanguages [] = $locale->getLanguage();
            return $this->getTranslationWithLanguageFallback($config, $label, $locale, $parsedLanguages);
        }

        return $label;
    }
}
