<?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 Neos\Flow\Mvc\ActionRequest;
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);
    }

    public function getUpdatedAtFromRequestedArticle(ActionRequest $request): ?int
    {
        $pluginArguments = $request->getPluginArguments();
        $articleId = $pluginArguments['plugin']['article']['__identity'] ?? null;
        if ($articleId === null) {
            return null;
        }

        $article = $this->articleRepository->find($articleId);
        if ($article === null) {
            return null;
        }

        $updatedAt = $article->getUpdatedAt();
        if ($updatedAt === null) {
            return null;
        }

        return $updatedAt->getTimestamp();
    }

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