<?php declare(strict_types=1);
namespace Newland\NeosFiltering\Service;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Neos\Flow\I18n\Translator;
use Neos\Utility\SchemaValidator;
use Neos\Flow\Annotations as Flow;
use Symfony\Component\Yaml\Yaml;
use Neos\Flow\Validation\Error;
use function Safe\file_get_contents;

class FilterDictionaryService
{

    /**
     * @var Translator
     * @Flow\Inject()
     */
    protected $translator;

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

    public function getFilterGroup(string $filterGroup, ?string $language): array
    {
        $filterItems = $this->getConfiguredGroups($filterGroup);
        if (empty($filterItems)) {
            throw new \InvalidArgumentException(
                "Invalid data source for filterGroup configuration\n"
            );
        }
        if (array_key_exists('isLanguageAware', $filterItems) && $filterItems['isLanguageAware'] ?? null) {
            $filterItems = $this->parseOptionsPerLanguage($language, $filterItems);
        }

        $filterItems = $this->applyLanguageLabelsAndGroup($filterItems, $filterGroup);

        return $filterItems['items'];
    }

    protected function applyLanguageLabelsAndGroup(array $data, string $filterGroup): array
    {
        foreach ($data['items'] as &$item) {
            if (!array_key_exists('label', $item)) {
                $item['label'] = $this->translator->translateById(
                    $item['i18n']['id'] ?? $item['value'],
                    $item['i18n']['arguments'] ?? [],
                    null,
                    null,
                    $item['i18n']['source'] ?? $data['translations']['i18n']['source'] ?? null,
                    $item['i18n']['package'] ?? $data['translations']['i18n']['package'] ?? null
                ) ?? $item['value'];
            }
            $item['group'] = $this->translator->translateById(
                'group.' . $filterGroup,
                [],
                null,
                null,
                $data['translations']['sections']['source'] ?? null,
                $data['translations']['sections']['package'] ?? null
            ) ?? '';
        }
        return $data;
    }

    private function parseOptionsPerLanguage(?string $language, array $arguments): array
    {
        $arguments['items'] = $arguments['items'][$language] ?? [];
        return $arguments;
    }

    private function getConfiguredGroups(string $filterGroup): array
    {
        return $this->filterGroups[$filterGroup] ?? [];
    }
}
