<?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\CategoryRepository;

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

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

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

    /**
     * @var CategoryRepository
     * @Flow\Inject()
     */
    protected $categoryRepository;

    /**
     * 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 = [])
    {
        $language = $this->getLanguage($node);
        if ($language !== null) {
            $this->categoryRepository->setLanguage($language);
        }

        $result = $this->categoryRepository->withLanguage(
            $this->getLanguage($node),
            function () {
                $query = $this->categoryRepository->createQueryBuilder('category');
                $query->select('category.Persistence_Object_Identifier as value', 'category.title as label');
                $query->distinct(true);
                $query->innerJoin('category.events', 'events');
                $query->orderBy('category.title', 'ASC');
                return $query->getQuery()->execute(null, Query::HYDRATE_ARRAY);
            }
        );
        return $result;
    }
}
