<?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
    {
        if (!$identifier) {
            return null;
        }
        return $this->articleRepository->findByIdentifier($identifier);
    }

    /**
     * @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 $methodName === 'findByIdentifier' || $methodName === 'url';
    }
}
