<?php

namespace App\EventSubscriber\Blog;

use App\Core\Entity\EntityInterface;
use App\Core\Event\EntityManager\EntityManagerEvent;
use App\Core\EventSubscriber\EntityManagerEventSubscriber;
use App\Core\Notification\MailNotifier;
use App\Core\Setting\SettingManager;
use App\Core\Site\SiteRequest;
use App\Entity\Blog\PostFollow;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * class PostFollowEventSubscriber.
 *
 * @author Simon Vieille <simon@deblan.fr>
 */
class PostFollowEventSubscriber extends EntityManagerEventSubscriber
{
    protected MailNotifier $notifier;
    protected UrlGeneratorInterface $urlGenerator;
    protected SettingManager $settingManager;
    protected SiteRequest $siteRequest;

    public function __construct(
        MailNotifier $notifier,
        UrlGeneratorInterface $urlGenerator,
        SettingManager $settingManager,
        SiteRequest $siteRequest
    ) {
        $this->notifier = $notifier;
        $this->urlGenerator = $urlGenerator;
        $this->settingManager = $settingManager;
        $this->siteRequest = $siteRequest;
    }

    public function supports(EntityInterface $entity)
    {
        return $entity instanceof PostFollow;
    }

    public function onCreate(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        $this->notifier
            ->init()
            ->setFrom($this->settingManager->get('email_sender')->getValue())
            ->addRecipient($event->getEntity()->getComment()->getEmail())
            ->setSubject('[Deblan] Confirmer votre e-mail')
            ->notify('mail/post_follow_subscription.html.twig', [
                'entity' => $event->getEntity(),
                'links' => [
                    'post' => $this->urlGenerator->generate('blog_menu_post', [
                        'post' => $event->getEntity()->getPost()->getId(),
                        'slug' => $event->getEntity()->getPost()->getSlug(),
                        '_domain' => $this->siteRequest->getDomain(),
                    ], UrlGeneratorInterface::ABSOLUTE_URL),
                    'enable' => $this->urlGenerator->generate('blog_tech_follow_enable', [
                        'hash' => $event->getEntity()->getHash(),
                        '_domain' => $this->siteRequest->getDomain(),
                    ], UrlGeneratorInterface::ABSOLUTE_URL),
                    'disable' => $this->urlGenerator->generate('blog_tech_follow_disable', [
                        'hash' => $event->getEntity()->getHash(),
                        '_domain' => $this->siteRequest->getDomain(),
                    ], UrlGeneratorInterface::ABSOLUTE_URL),
                ],
            ], 'text/plain')
        ;
    }
}
