<?php
namespace Newland\Toubiz\Events\Neos\DataSource;

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

use Doctrine\ORM\Query;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\I18n\Translator;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Newland\NeosCommon\Translation\LanguageAwareDataSource;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventTagRepository;

/**
 * @Flow\Scope("singleton")
 */
class TagsDataSource extends AbstractDataSource
{
    use LanguageAwareDataSource;

    protected static $identifier = 'newland-toubiz-events-neos-tags';

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

    /**
     * @var EventTagRepository
     * @Flow\Inject()
     */
    protected $eventTagRepository;

    public function getData(NodeInterface $node = null, array $arguments = []): array
    {
        $language = $this->getLanguage($node);
        if ($language !== null) {
            $this->eventTagRepository->setLanguage($language);
        }

        return $this->eventTagRepository->createQueryBuilder('entity')
            ->distinct(true)
            ->select(
                [
                    'entity.Persistence_Object_Identifier AS value',
                    'entity.keyword as label',
                ]
            )
            ->innerJoin('entity.events', 'events')
            ->orderBy('entity.keyword')
            ->getQuery()
            ->execute(null, Query::HYDRATE_ARRAY);
    }
}
