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

/*
 * 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\I18n\Translator;
use Newland\NeosFiltering\Service\FilterDictionaryService;
use Newland\Toubiz\Poi\Neos\Domain\Model\FilterAttribute;
use Neos\Flow\Annotations as Flow;

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

    /**
     * @var FilterDictionaryService
     * @Flow\Inject()
     */
    protected $filterDictionaryService;

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

    public function findConfiguredByArticleType(int $type, ?string $language): array
    {
        $groups = $this->getConfiguredAttributeGroups($type, $language);
        $ids = [];
        $data = [];

        foreach ($groups as $attributes) {
            $parsedAttributes = array_map(function ($attribute) use (&$ids) {
                $id = 'attribute.' . $attribute['value'];
                if (\in_array($id, $ids, true)) {
                    return null;
                }
                $ids[] = $id;

                return new FilterAttribute(
                    $id,
                    $attribute['label'],
                    $attribute['value'],
                    $attribute['group']
                );
            }, $attributes);
            $data = array_merge($data, $parsedAttributes);
        }

        return array_filter($data);
    }

    protected function getConfiguredAttributeGroups(int $type, ?string $language): array
    {
        $data = [];
        $configuredAttributes = $this->attributeConfiguration['articleTypeFilters'][$type] ?? [];
        foreach ($configuredAttributes as $group) {
            $data[] = $this->filterDictionaryService->getFilterGroup($group, $language);
        }
        return $data;
    }
}
