<?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\NeosCommon\Service\ContextService;
use Newland\Toubiz\Sync\Neos\Domain\Filter\ArticleFilter;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

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

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

    /**
     * @Flow\Inject()
     * @var ArticleRepository
     */
    protected $articleRepository;

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

    /**
     * @Flow\Inject()
     * @var ContextService
     */
    protected $contextService;

    /**
     * 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 = [])
    {
        if ($node === null) {
            return [];
        }

        $site = $this->contextService->siteFromReferenceNode($node);
        if ($site === null) {
            return [];
        }

        $data = [];

        $filter = new ArticleFilter();
        $filter->setCurrentSite($site->getNodeName());
        $filter->setMainType($arguments['mainType'] ?? null);

        $this->articleRepository->setLanguage($this->getLanguage($node));

        $articles = $this->articleRepository->findAllForDataSource($filter);
        foreach ($articles as $article) {
            $data[] = [
                'label' => $article['article_name'],
                'value' => $article['article_identifier'],
                'group' => $article['category_title'],
            ];
        }

        return $data;
    }
}
