<?php

namespace Lc\SovBundle\EventSubscriber\User;

use Doctrine\ORM\EntityManagerInterface;

use Lc\SovBundle\Doctrine\EntityInterface;
use Lc\SovBundle\Doctrine\Extension\SortableInterface;
use Lc\SovBundle\Doctrine\Extension\StatusInterface;
use Lc\SovBundle\Doctrine\Extension\TreeInterface;
use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
use Lc\SovBundle\Model\User\UserInterface;
use Lc\SovBundle\Repository\AbstractRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserPasswordEventSubscriber implements EventSubscriberInterface
{
    protected $passwordEncoder;

    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->passwordEncoder = $passwordEncoder;
    }

    public static function getSubscribedEvents()
    {
        return [
                EntityManagerEvent::PRE_CREATE_EVENT => ['setUserPasswordIfNull'],
        ];
    }

    public function setUserPasswordIfNull(EntityManagerEvent $event)
    {
        $entity = $event->getEntity();

        if ($entity instanceof UserInterface) {
            if ($entity->getPassword() == null) {
                $password = $this->passwordEncoder->encodePassword($entity, $entity->generatePassword());
                $entity->setPassword($password);
            }
        }
    }


}