<?php

namespace App\EventSubscriber;

use App\Service\Booker;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Presta\SitemapBundle\Event\SitemapPopulateEvent;
use Presta\SitemapBundle\Service\UrlContainerInterface;
use Presta\SitemapBundle\Sitemap\Url\UrlConcrete;

class SitemapSubscriber implements EventSubscriberInterface
{
	/**
	 * @var UrlGeneratorInterface
	 */
	private $urlGenerator;

	/**
	 * @var BlogPostRepository
	 */
	private $blogPostRepository;

	/**
	 * @param UrlGeneratorInterface $urlGenerator
	 * @param BlogPostRepository    $blogPostRepository
	 */
	public function __construct(UrlGeneratorInterface $urlGenerator, Booker $booker)
	{
		$this->urlGenerator = $urlGenerator;
		$this->booker = $booker;
	}

	/**
	 * @inheritdoc
	 */
	public static function getSubscribedEvents()
	{
		return [
			SitemapPopulateEvent::ON_SITEMAP_POPULATE => 'populate',
		];
	}

	/**
	 * @param SitemapPopulateEvent $event
	 */
	public function populate(SitemapPopulateEvent $event): void
	{
		$this->registerBlogPostsUrls($event->getUrlContainer());
	}

	/**
	 * @param UrlContainerInterface $urls
	 */
	public function registerBlogPostsUrls(UrlContainerInterface $urls): void
	{
		$sectionsHierarchy = $this->booker->getSectionsHierarchyWithImages();
		foreach ($sectionsHierarchy as $gender => $g) {
			foreach ($g as $s) {
				$urls->addUrl(
					new UrlConcrete(
						$this->urlGenerator->generate(
							'list',
							['gender' => $gender, 'section' => $s['slug']],
							UrlGeneratorInterface::ABSOLUTE_URL
						)
					),
					'list'
				);
			}
		}
		$allModels = $this->booker->getAllModels();
		foreach ($allModels as $m) {;
			$urls->addUrl(
				new UrlConcrete(
					$this->urlGenerator->generate(
						'model',
						['slug' => $m->display, 'nb' => $m->displayNb != 1 ? $m->displayNb : null],
						UrlGeneratorInterface::ABSOLUTE_URL
					)
				),
				'model'
			);
		}
		$urls->addUrl(
			new UrlConcrete(
				$this->urlGenerator->generate(
					'become',
					['lang' => 'en'],
					UrlGeneratorInterface::ABSOLUTE_URL
				)
			),
			'become'
		);
		$urls->addUrl(
			new UrlConcrete(
				$this->urlGenerator->generate(
					'become',
					['lang' => 'fr'],
					UrlGeneratorInterface::ABSOLUTE_URL
				)
			),
			'become'
		);
	}
}
