<?php declare(strict_types=1);

namespace Newland\Toubiz\Map\Neos\Tests\Unit\Serialization\Markers;

use Neos\ContentRepository\Domain\Model\Node;
use Newland\NeosCommon\LinkHandler\LinkingService;
use Newland\NeosCommon\Service\ControllerContextFactory;
use Newland\Toubiz\Map\Neos\Provider\Contract\ProviderContext;
use Newland\Toubiz\Map\Neos\Provider\DefaultProviders\Links;

class LinksTest extends MarkerSerializerTestCase
{
    /** @var Links */
    protected $subject;

    /** @var ControllerContextFactory */
    protected $controllerContextFactory;

    /** @var LinkingService */
    protected $linkingService;

    public function setUp(): void
    {
        parent::setUp();
        $this->subject = $this->objectManager->get(Links::class);
        $this->controllerContextFactory = $this->objectManager->get(ControllerContextFactory::class);
        $this->linkingService = $this->objectManager->get(LinkingService::class);
    }

    public function testResolvesInternalUrls(): void
    {
        $target = $this->initializeNode('/sites/foo/baz', 'live', $this->site, [ 'uriPathSegment' => '___super_unique_uri_segment___' ], 'de', 'Neos.NodeTypes:Page');
        $targetUrl = $this->linkingService->createNodeUri(
            $this->controllerContextFactory->initializeFakeControllerContext($this->node),
            $target
        );

        $node = $this->initializeLinksNode([ 'uri' => sprintf('node://%s', $target->getIdentifier()) ]);
        $results = $this->subject->getMarkers(new ProviderContext($this->mapNode, null), 0, 100);

        $this->assertCount(1, $results);
        $this->assertEquals($targetUrl, array_values($results)[0]->url);
        $this->assertContains('__super_unique_uri_segment__', array_values($results)[0]->url);
    }

    public function testResolvesExternalUrls(): void
    {
        $node = $this->initializeLinksNode([ 'uri' => 'https://google.com' ]);
        $results = $this->subject->getMarkers(new ProviderContext($this->mapNode, null), 0, 100);
        $this->assertCount(1, $results);
        $this->assertEquals('https://google.com', array_values($results)[0]->url);
    }

    public function testDoesNothingIfNoUrlTargetGiven(): void
    {
        $node = $this->initializeLinksNode([ 'uri' => null ]);
        $results = $this->subject->getMarkers(new ProviderContext($this->mapNode, null), 0, 100);
        $this->assertCount(0, $results);
    }

    private function initializeLinksNode(array $properties = []): Node
    {
        return $this->initializeNode(
            '/sites/foo/main/map/children/filter-item/foo-child',
            'live',
            $this->site,
            $properties,
            'de',
            'Newland.Toubiz.Map.Neos:Map.Markers.Link'
        );
    }

}
