<?php
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 Doctrine\ORM\Query;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\PersistenceManagerInterface;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Newland\NeosCommon\Translation\LanguageAwareDataSource;
use Newland\Toubiz\Sync\Neos\Domain\Repository\CategoryRepository;

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

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

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

    /**
     * @Flow\Inject()
     * @var PersistenceManagerInterface
     */
    protected $persistenceManager;

    /**
     * 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 = null;
        if ($node !== null && $node->hasProperty('articleType')) {
            $type = $node->getProperty('articleType');
        } elseif (array_key_exists('articleType', $arguments)) {
            $type = $arguments['articleType'];
        }

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