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

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
use Newland\Toubiz\Poi\Neos\Service\ArticleUrlService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

class ArticleHelper implements ProtectedContextAwareInterface
{

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

    /**
     * @var ArticleUrlService
     * @Flow\Inject()
     */
    protected $articleUrlService;

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

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

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

        if (!($article instanceof Article)) {
            return '#';
        }

        return $this->articleUrlService->generateUrlByCurrentNode($article, $node);
    }

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