<?php declare(strict_types=1);

namespace Newland\Toubiz\Map\Neos\Provider\DefaultProviders;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\ContentRepository\Domain\Projection\Content\TraversableNodeInterface;
use Newland\NeosCommon\Service\NodeService;
use Newland\Toubiz\Map\Neos\Provider\MapDataProvider;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;
use Neos\Flow\Annotations as Flow;

/**
 * @MapDataProvider()
 */
class SelectedArticles extends SubnodeBasedMarkerProvider
{
    use ArticleFormatting;
    protected $nodeType = 'Newland.Toubiz.Map.Neos:Map.Markers.SelectedArticles';

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

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

    public function markersForNode(Node $node, int $offset, int $limit): array
    {
        $articleIds = $node->getProperty('articles') ?: [];

        $markers = [];
        if (!empty($articleIds)) {
            $markers = $this->buildMarkersFromArticleIds(
                array_slice($articleIds, $offset, $limit),
                $node
            );
        }

        return $markers;
    }

    protected function buildMarkersFromArticleIds(array $articleIds, Node $node): array
    {
        $alwaysDisplayPolygon = (bool) $node->getProperty('alwaysDisplayPolygon');
        $color = $node->getProperty('tourColor');

        $language = $this->nodeService->getLanguage($node);
        $articles = $this->articleRepository->withLanguage(
            $language,
            function () use ($articleIds) {
                return $this->articleRepository->findByIdentifiers($articleIds);
            }
        );

        $markers = [];
        foreach ($articles as $article) {
            /** @var Article $article */
            $marker = $this->articleToMarker($article, $node, !$alwaysDisplayPolygon);
            if (!$marker) {
                continue;
            }

            if ($marker->tour) {
                $marker->tour['alwaysDisplayPolygon'] = $alwaysDisplayPolygon;
                $marker->tour['color'] = $color;
            }

            $markers[] = $marker;
        }
        return $markers;
    }

    public function numberOfMarkersForNode(Node $node): int
    {
        return count($node->getProperty('articles') ?: []);
    }
}
