<?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);
        $data = [];

        foreach ($groups as $attributes) {
            $parsedAttributes = array_map(function ($attribute) {
                $id = 'attribute.' . $attribute['value'];
                return new FilterAttribute(
                    $id,
                    $attribute['label'],
                    $attribute['value'],
                    $attribute['group']
                );
            }, $attributes);
            $data = array_merge($data, $parsedAttributes);
        }

        return $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;
    }
}
