<?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 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\Api\Constants\EventType;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventRepository;

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

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

    /**
     * @Flow\Inject()
     * @var EventRepository
     */
    protected $eventRepository;

    /**
     * @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.
     *
     * @param NodeInterface $node The node that is currently edited (optional)
     * @param array $arguments Additional arguments (key / value)
     * @return mixed JSON serializable data
     * @api
     */
    public function getData(NodeInterface $node = null, array $arguments = [])
    {
        if ($node === null) {
            return [];
        }

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

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

        return $this->getEvents();
    }

    protected function getEvents(): array
    {
        return $this->eventRepository->findAllForDataSource();
    }
}
