<?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 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\Filter\CategoryFilter;
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 = [])
    {
        $this->categoryRepository->setLanguage($this->getLanguage($node));

        // TODO: Deprecated, refactor in 1.2.0
        $filter = new CategoryFilter();
        $filter->setOrderBy([ 'category.title' => 'ASC' ]);

        if ($node !== null && $node->hasProperty('articleType')) {
            $filter->setArticleMainType($node->getProperty('articleType'));
        }

        $data = [];
        $categories = $this->categoryRepository->findByFilter($filter);
        foreach ($categories as $category) {
            $data[] = [
                'label' => $category->getTitle(),
                'value' => $this->persistenceManager->getIdentifierByObject($category),
            ];
        }

        return $data;
    }
}
