<?php
namespace Newland\Toubiz\Events\Neos\Eel\Helper;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
use Newland\Toubiz\Events\Neos\Service\EventUrlService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventRepository;

class EventHelper implements ProtectedContextAwareInterface
{
    /**
     * @var EventRepository
     * @Flow\Inject()
     */
    protected $eventRepository;

    /**
     * @var EventUrlService
     * @Flow\Inject()
     */
    protected $eventUrlService;

    public function findByIdentifier(?string $identifier): ?Event
    {
        return $this->eventRepository->findByIdentifier($identifier);
    }

    /**
     * @param string[]|null $identifiers
     * @return Event[]
     */
    public function findByIdentifiers(?array $identifiers): array
    {
        return $this->eventRepository->findByIdentifiers((array) $identifiers);
    }

    /**
     * @param Event|string $event
     */
    public function url($event, NodeInterface $node): ?string
    {
        if (\is_string($event)) {
            $event = $this->eventRepository->findByIdentifier($event);
        }

        if (!($event instanceof Event)) {
            return '#';
        }

        return $this->eventUrlService->generateUrlByCurrentNode($event, $node);
    }

    /**
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName): bool
    {
        return \in_array($methodName, [ 'findByIdentifier', 'findByIdentifiers', 'url' ]);
    }
}
