<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\PageFrame;

use Newland\NeosCommon\Service\NodeService;
use Newland\PageFrameProvider\Dimensions\AlternativeDimensionProvider;
use Newland\PageFrameProvider\Service\PageFrameContextService;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Poi\Neos\Service\ArticleUrlService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

class ArticleDimensionProvider implements AlternativeDimensionProvider
{
    /**
     * @var ArticlePageFrameHelper
     * @Flow\Inject()
     */
    protected $helper;

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

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

    /**
     * @var PageFrameContextService
     * @Flow\Inject()
     */
    protected $pageFrameContext;

    /**
     * @var NodeService
     * @Flow\Inject()
     */
    protected $nodeService;

    /**
     * @inheritDoc
     */
    public function getAlternativeDimensions(string $dimensionName): array
    {
        $article = $this->helper->getArticle();
        if ($dimensionName !== 'language' || !$article) {
            return [];
        }

        $variants = $this->articleRepository->findLanguageVariants($article);
        return array_filter(array_map([ $this, 'articleUrl' ], $variants));
    }

    private function articleUrl(Article $article): ?string
    {
        $node = $this->nodeService->nodeInLanguage($this->pageFrameContext->getNode(), $article->getLanguage());
        if (!$node) {
            return null;
        }
        return $this->articleUrlService->generateUrlByCurrentNode($article, $node, true);
    }
}
