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

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cache\CacheManager;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

/**
 * @Flow\Scope("singleton")
 */
class ArticleDataSource extends AbstractDataSource
{
    protected static $identifier = 'newland-toubiz-map-neos-articles';
    const CACHE_NAME = 'Newland_Toubiz_map_neos-ArticleDataSource';
    const CACHE_LIFETIME_SECONDS = 60 * 60 * 24;

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

    /**
     * @Flow\Inject()
     * @var CacheManager
     */
    protected $cacheManager;

    /**
     * Get data
     *
     * The return value must be JSON serializable data structure.
     *
     * @param NodeInterface $node The node that is currently edited (optional)
     * @param array $arguments Additional arguments (key / value)
     * @return mixed JSON serializable data
     * @api
     * @throws \Neos\Cache\Exception\NoSuchCacheException
     */
    public function getData(NodeInterface $node = null, array $arguments)
    {
        $cache = $this->cacheManager->getCache(self::CACHE_NAME);

        // Note: Using one cache key for all nodes since the result does not change from node to node.
        $cacheKey = 'articles';
        if ($cache->has($cacheKey)) {
            return $cache->get($cacheKey);
        }

        $articles = $this->articleRepository
            ->createQueryBuilder('article')
            ->select('article.Persistence_Object_Identifier as value, article.name as label')
            ->getQuery()
            ->execute();

        $cache->set($cacheKey, $articles, [], self::CACHE_LIFETIME_SECONDS);
        return $articles;
    }
}
