<?php
namespace Newland\Toubiz\Events\Neos\Sitemap;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Mvc\Controller\ControllerContext;
use Neos\Neos\Domain\Model\Domain;
use Neos\Neos\Domain\Service\ContentContext;
use Newland\NeosCommon\Sitemap\SitemapProvider;
use Neos\Flow\Annotations as Flow;
use Newland\NeosCommon\Sitemap\SitemapUrl;
use Newland\NeosCommon\Service\ControllerContextFactory;
use Newland\Toubiz\Events\Neos\Service\EventUrlService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventRepository;

/**
 * @Flow\Scope("singleton")
 */
class EventDetailSitemapProvider implements SitemapProvider
{

    /**
     * @var EventRepository
     * @Flow\Inject()
     */
    protected $eventRepository;

    /**
     * @var EventUrlService
     * @Flow\Inject()
     */
    protected $eventUrlService;

    /**
     * @Flow\Inject()
     * @var ControllerContextFactory
     */
    protected $contextFactory;

    /**
     * @param NodeInterface $site
     * @return SitemapUrl[]
     */
    public function getPages(NodeInterface $site): array
    {
        $pages = [];
        $context = $this->contextFactory->initializeFakeControllerContext($site);

        foreach ($this->eventRepository->findAll() as $event) {
            $url = $this->eventToSitemapUrl($event, $context, $this->domain($site));
            if ($url) {
                $pages[] = $url;
            }
        }

        return $pages;
    }

    private function eventToSitemapUrl(Event $event, ControllerContext $context, Domain $domain): ?SitemapUrl
    {
        $url = $this->eventUrlService->generateUrl($event, $context);
        if (!$url) {
            return null;
        }

        $url = $this->prependDomainIfRelative($url, $domain);
        return new SitemapUrl($url);
    }

    private function prependDomainIfRelative(string $url, Domain $domain): string
    {
        if (strpos($url, 'http') !== false) {
            return $url;
        }

        $domainWithScheme = clone $domain;
        $domainWithScheme->setScheme($domain->getScheme() ?? 'http');
        return ((string) $domainWithScheme) . '/' . ltrim($url, '/');
    }


    /**
     * @param NodeInterface $site
     * @return Domain
     */
    private function domain(NodeInterface $site): Domain
    {
        $contentContext = $site->getContext();
        if (!($contentContext instanceof ContentContext)) {
            return new Domain();
        }

        $domain = $contentContext->getCurrentSite()->getPrimaryDomain();
        return $domain ?? new Domain();
    }
}
