<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class AddErrorMessageValidationListener implements EventSubscriberInterface
{
    private $flashBag;

    private $requestStack;

    private $translator;

    public function __construct(FlashBagInterface $flashBag,
        RequestStack $requestStack,
        TranslatorInterface $translator
    ) {
        $this->flashBag = $flashBag;
        $this->requestStack = $requestStack;
        $this->translator = $translator;
    }

    public static function getSubscribedEvents()
    {
        return [
            FormEvents::POST_SUBMIT => 'onPostSubmit',
        ];
    }

    public function onPostSubmit(FormEvent $event)
    {
        if ($event->getForm()->isValid()) {
            return;
        }

        $this->flashBag->add('error', $this->translator->trans('form.error', [], 'validators'));
    }
}
