<?php

namespace NPS\Factory;

use NPS\Model\User;
use NPS\Repository\UserRepository;
use NPS\Entity\UserEntity;
use NPS\Entity\IEntity;
use NPS\DependencyInjection\EventDispatcher;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;


/**
 * User object factory 
 * @author Lukas Korinek
 */
class UserFactory implements IObjectFactory
{
    use TMemorizedFactory;

    /** @var EntityManagerInterface $em */
    protected $em;

    /** @var UserPasswordEncoderInterface $encoder */
    protected $encoder;

    public function __construct(EntityManagerInterface $em, UserPasswordEncoderInterface $encoder)
    {
        $this->em = $em;
        $this->encoder = $encoder;
    }

    /**
     * @inheritdoc
     */
    public function make(IEntity $entity)
    {
        return $this->load($entity, function($entity)
        {
            if(!$entity->getId())
            {
                $this->em->persist($entity);
            }

            return new User($entity, $this->encoder);            
        });
    }

    
    /**
     * Creates a new user
     * @param string $email 
     * @param string $username 
     * @param string $password
     * @param array $roles
     * @return User|null
     */
    public function create($email, $username, $password, array $roles)
    {
        $entity = UserEntity::create([
            'email' => $email,
            'username' => ucwords(trim($username)),
            'roles' => implode(',', $roles) ?: 'ROLE_USER',
            
        ]);

        $user = $this->make($entity);
        $user->updatePassword($password);
        
        return $user;
    }
}

