<?php

namespace App\EventListener;

use App\Entity\User;
use App\Entity\UserLogConnections;
use Doctrine\ORM\EntityManagerInterface;
use App\Component\EntityManagerAwareTrait;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

/**
 * @package App\EventListener
 */
class SecuritySubscriber implements EventSubscriberInterface
{
    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(private EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents(): array
    {
        return [
            LoginSuccessEvent::class => 'onLoginSuccess',
        ];
    }

    public function onLoginSuccess(LoginSuccessEvent $event): void
    {
        $user = $event->getUser();
        // dd($event);

        if ($user instanceof User) {

            $log_connection = new UserLogConnections();
            $log_connection->setUser($user);
            
            $this->em->persist($log_connection);
            $this->em->flush();
        }
    }
}