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

/*
 * 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\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Newland\NeosCommon\Translation\LanguageAwareDataSource;
use Newland\Toubiz\Poi\Neos\Domain\Repository\FilterAttributeRepository;

/**
 * Categories data source service.
 *
 * @Flow\Scope("singleton")
 */
class AttributesDataSource extends AbstractDataSource
{
    use LanguageAwareDataSource;

    /**
     * @var string Data source identifier.
     */
    protected static $identifier = 'newland-toubiz-poi-neos-attributes';

    /**
     * @Flow\Inject()
     * @var FilterAttributeRepository
     */
    protected $attributeRepository;

    /**
     * Get requested data from source.
     *
     * The return value must be JSON serializable data structure.
     *
     * @api
     * @param NodeInterface $node The node that is currently edited (optional)
     * @param array $arguments Additional arguments (key / value)
     * @return mixed JSON serializable data
     */
    public function getData(NodeInterface $node = null, array $arguments = [])
    {
        $type = '';
        if ($node !== null && $node->hasProperty('articleType')) {
            $type = $node->getProperty('articleType');
        } elseif (array_key_exists('articleType', $arguments)) {
            $type = $arguments['articleType'];
        }

        if ($node !== null) {
            $language = $node->getDimensions()['language'][0] ?? null;
        }

        return $this->attributeRepository->findConfiguredByArticleType((int) $type, $language ?? null);
    }
}
